3

In the example below, how to preserve part of a pattern? The pattern search must include closing tag </h3> as spans elsewhere must not be targeted.

Example: remove only </span> from </span> some text </h3>:

regEx.Pattern = "</span>[^>]*</h3>"
hr2 = regEx.Replace(hr2,"[^>]*</h3>")  '<- does not work
3
  • Try regEx.Pattern = "</span>([^>]*)</h3>" // hr2 = regEx.Replace(hr2,"$1</h3>") Commented Jul 22, 2015 at 14:55
  • This did the same as what did not work above - passed it through, in this case as '$1'. Commented Jul 22, 2015 at 15:12
  • Sorry, your solution correct. Did not notice the brackets in the pattern above that make $1 work. Thanks for fast help! Commented Jul 22, 2015 at 15:17

1 Answer 1

3

You need to set a capturing group and use a back reference in the replacement pattern.

regEx.Pattern = "</span>([^>]*)</h3>"
hr2 = regEx.Replace(hr2,"$1</h3>")

Or

regEx.Pattern = "</span>([^>]*</h3>)"
hr2 = regEx.Replace(hr2,"$1")
Sign up to request clarification or add additional context in comments.

3 Comments

It may be worth considering using the non-greedy expression .*? instead of [^>]* in case there are other tags between </span> and </h3>.
Yes, but we do not know the input text. Surely .*? will also capture the tags before </h3> then.
</span>(.*?)</h3> would capture tags between </span> and </h3>, yes.

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.