2

<name>My name is Tom but people call me as XYZ but my actual name is Tommy!</name>

  • Now, I want to find "Tom" inside the specified xml tag, and replace it with Harry.
  • Finding, multiple instances of "Tom" and replace it with "Harry" from the string inside the specified XML tag.

Example: (?<=<name>)[a-zA-Z]*(Tom)[a-zA-Z]*(?=<\/name>),

  • This is not able to find the word "Tom" from the specified string between XML tag.
2
  • Can <name> tag contain other tags? Commented Feb 6, 2018 at 12:26
  • No, it contains only <name></name> tags. There are so many tags in my XML file, but I'm targeting only <name> tags. And <name> does not contain any other tags. Commented Feb 6, 2018 at 12:37

2 Answers 2

1

Since the name tag cannot have any other tags inside, the regex that can solve the issue is

(?:\G(?!^)|<name>)[^<]*?\K\bTom\b

See the regex demo. Replace with Harry.

Details

  • (?:\G(?!^)|<name>) - the end of the previous successful match (\G(?!^)) or (|) the <name> substring
  • [^<]*? - any 0+ chars other than <, as few as possible
  • \K - match reset operator
  • \bTom\b - whole word Tom (remove \b word boundaries if you need to match Tom in Tommy).

NOTE: If you also want to match Tommy, replace \bTom\b with \bTom(?:my)?\b.

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

Comments

1

Find what : (?<=<name>)(.*?)(Tom)(?=\b.*</name>)
Replace with : $1Harry

Detail :
Balise name : (?<=<name>)
Anything between name and Tom(.*?)
Tom (Tom)
A boudary to check the end of the word Tom(?=\b
Anything between tom and the closing name balise .*
The closing balise </name>)

Reinject what's between the balise name and tom$1
Replacing Tom by HarryHarry

Comments

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.