Hi,
I want to replace a text in a string using a regex. In particular I want to select replace some words in a text satisfying the following condition:
“[\s(±/]\$" + word + "[\s)±/]”
the point is that I want just to replace “word” and keeping the “[\s(±/]" before (not the “$”) and the "[\s)±/]” after (I hope you got what I mean). So what to put in the rg.ReplacementPattern as below?
Thanks!
rg.SearchPattern = "[\\s(*+-/]\\$" + word + "[\\s)*+-/]"
rg.ReplacementPattern = ????
rg.Options.replaceAllMatches = True
text = rg.Replace(text)
Wrap the parts you want to keep in parens and use $1 and $2 in the replacement pattern.
Glad to help. Be careful of what’s in the word
variable, though. If word
contains a regex token like * or +, you are going to get an exception or an incorrect result.
An easy fix if it’s a concern:
word = "\\Q" + word.ReplaceAllB( "\\E", "\\\\EE\\Q" ) + "\\E"
Anything that appears between the “\Q” and “\E” tokens will be taken literally.
[quote=174847:@Kem Tekinay]Glad to help. Be careful of what’s in the word
variable, though. If word
contains a regex token like * or +, you are going to get an exception or an incorrect result.
An easy fix if it’s a concern:
word = "\\Q" + word.ReplaceAllB( "\\E", "\\\\EE\\Q" ) + "\\E"
Anything that appears between the “\Q” and “\E” tokens will be taken literally.[/quote]
Good to know, thanks. However it should not apply to my particular case.