user1697999
user1697999

Reputation: 215

Regex: Add text inside xml tags if not exists

I have a set of xml tags:

<foo></foo>

If the tags have the word "bar" inside I do nothing

<foo>dog bar cat</foo> -> <foo>dog bar cat</foo>

If the tags don't have the word "bar" inside I add it to the end of the text

<foo>dog cat</foo> -> <foo>dog cat bar</foo>\

"bar" can potentially be anywhere in between the tags. How can I do this kind of replace using regex?

I have tried variations of the following but it isn't working:

(<foo>.*?)((?:bar)*)(.*?</foo>) replace with $1 bar$3

I am getting frustrated with this one and could use some help.

Upvotes: 0

Views: 238

Answers (1)

nhahtdh
nhahtdh

Reputation: 56829

Pattern to search for:

<foo>((?:(?!bar|</foo>).)*)</foo>

Replacement string:

<foo>$1 bar</foo>

If <foo> tag has another nested <foo> tag inside, only the innermost pair is touched.

Note that the pattern above uses negative look-ahead (?!pattern), which is supported by PCRE (PHP), .NET, Java, JavaScript, Boost library (Notepad++), Perl...

Upvotes: 1

Related Questions