regex replace problem.

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?
 
J

Jesse Houwing

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.
 
J

Jeremy

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

regex help 1
Help with regular expression 2
Add value in string 1
Regex help needed 1
Regex Usage, or use Substring? 3
Loop is slow trying array code 17
Help with Regex 5
Replace email 1

Top