1

I would like to replace all names in an XML file tagged by with let's say xyz. In other words, replace everything (including whitespace) between the tags. What am I doing wrong?

Search: (<name>)(.*)(</name>)
Replace: \1xyz\3
1
  • 2
    What goes wrong when you try it? Commented Nov 2, 2012 at 12:44

1 Answer 1

13

You are trying to parse XML with regular expressions.

However, what you are doing wrong anyway is using a greedy repetition. This will go all the way from the first <name> to the very last </name> (even if they do not belong together), because the .* will try to consume as much as possible while still fulfilling the match condition.. Use this instead:

Search: (<name>).*?(</name>)
Replace: \1xyz\2

Or to be on the safe side you can also escape the < and >, since they are meta-characters in some specific cases (not in this one though):

Search: (\<name\>).*?(\</name\>)
Replace: \1xyz\2

In both cases, this makes the .* ungreedy, i.e. it will consume as little as possible.

And make sure you upgrade to Notepad++ 6, because before that there were a few issues with Notepad++'s regex engine.

Lastly, as hoombar pointed out in a comment . by default matches every character except line break characters. In Notepadd++ you can change this behavior by ticking the . matches newline checkbox.

Sign up to request clarification or add additional context in comments.

4 Comments

you might also want to check the box ". matches new line"
I generally escape the <> to prevent unexpected behaviour \<\>
@Ariaan It's probably a matter of taste (I usually prefer the readability), and would only differ inside a named capturing group, wouldn't it?
@m.buettner You're correct, but I'd prefer to be prepared for reuse in larger regular expressions, in case you'd need to extend your expression. I don't think it's a bad habit when writing complicated expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.