tags:

views:

88

answers:

3

Is there a way that the Regex will check the first and the last character, but will replace only the IV and not the spaces.

Regex.Replace("This is IV item.", "[^A-Za-z0-9](IV)[^A-Za-z0-9]", "fourth");

Please don't tell me about MatchEvaluator and other Match based things, I need a one line solution, and one line doesn't mean combining code, it means using Replace method only.

Also I am not talking only about spaces, I am talking in general for any character, like: (

Once again, let me clear, I am not looking for anything other than some regex symbols that will match the characters but won't replace it and not this method:

Regex.Replace("This is IV item.", "([^A-Za-z0-9])(IV)([^A-Za-z0-9])", "$1fourth$3");

as this regex are parameters to some code that will automatically automatically uses $1 for some thing and I don't want to change that code, so is there a way so that $1 will be IV only, while checking that the previous character also.

+2  A: 

What you are looking for are so called look behinds and look aheads. Try using (?<=\ )IV(?!<=\ ) as a pattern.

winSharp93
+1 as is the what I was looking. Sorry, not accepting this cause I run into issues with the syntax given, so accepting the one with the example.
Priyank Bolia
I think you meant `(?<=\ )IV(?=\ )`. Anyway, the OP said the surrounding characters could be anything other than ASCII letters and digits, not just spaces.
Alan Moore
+5  A: 
Regex.Replace("This is IV item.", @"\bIV\b", "fourth");
Pent Ploompuu
what about "This is !IV item." I said it can be any symbol.
Priyank Bolia
This works for "This is !IV item." It fails for "This is \_IV\_ item though."
Mark Byers
The word boundary (\b) method is very simple and often all you need. If this isn't enough then you should use the look-behind/look-ahead solutions.
Pent Ploompuu
+1  A: 

It's not entirely clear from your question exactly what you want to accept and reject, but I think you need something like this:

Regex.Replace("This is IV item.", "(?<=[^A-Za-z0-9])(IV)(?=[^A-Za-z0-9])", "fourth");
Mark Byers
Yes this is what I want.
Priyank Bolia