regex replace problem.

  • Thread starter Thread starter Jeremy
  • Start date Start date
J

Jeremy

I am trying to replace a string "P" with "\P" as long as the string "P" does
not already have a "\" in front.

for my search string I've used @"([^\\]P)" so my regex replace statement is:

System.Text.RegularExpressions.Regex pR = new
System.Text.RegularExpressions.Regex(@"([^\\]P)");
string strResult = pR.Replace(@"This is a XP test X\P", @"\P");

The poblem is that the statement replaces XP with \P where I want it to be
X\P. Can I do this with a regex statement?
 
Hello Jeremy,
I am trying to replace a string "P" with "\P" as long as the string
"P" does not already have a "\" in front.

for my search string I've used @"([^\\]P)" so my regex replace
statement is:

System.Text.RegularExpressions.Regex pR = new
System.Text.RegularExpressions.Regex(@"([^\\]P)"); string strResult =
pR.Replace(@"This is a XP test X\P", @"\P");

The poblem is that the statement replaces XP with \P where I want it
to be X\P. Can I do this with a regex statement?

The easiest way is to use a negative look behind:

@"(?<!\)P"

The (?<! ... ) will check that the expression between the parentesis won't
match in front of the current position (e.g. in front of the P character).

Now you can easily replace with

@"\$0"

$0 will contain the contents of the matching regex, so if you later decide
you want to replace \R as well you can more easily change the expression to:

@"(?<!\)[PR]"

And the replace pattern will still work.
 
Thank!

Jesse Houwing said:
Hello Jeremy,
I am trying to replace a string "P" with "\P" as long as the string
"P" does not already have a "\" in front.

for my search string I've used @"([^\\]P)" so my regex replace
statement is:

System.Text.RegularExpressions.Regex pR = new
System.Text.RegularExpressions.Regex(@"([^\\]P)"); string strResult =
pR.Replace(@"This is a XP test X\P", @"\P");

The poblem is that the statement replaces XP with \P where I want it
to be X\P. Can I do this with a regex statement?

The easiest way is to use a negative look behind:

@"(?<!\)P"

The (?<! ... ) will check that the expression between the parentesis won't
match in front of the current position (e.g. in front of the P character).

Now you can easily replace with
@"\$0"

$0 will contain the contents of the matching regex, so if you later decide
you want to replace \R as well you can more easily change the expression
to:

@"(?<!\)[PR]"

And the replace pattern will still work.
 
Back
Top