1

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
  • If I may be so forward as to ask, why do you need a one-liner for this? Commented Jan 14, 2010 at 17:09
  • as already told the Regex Replace is in some other lib, which I don't want to modify. the Regex is input to that. So the question is about writing regex and not C# code. Commented Jan 14, 2010 at 17:13

3 Answers 3

5
Regex.Replace("This is IV item.", @"\bIV\b", "fourth");
Sign up to request clarification or add additional context in comments.

3 Comments

what about "This is !IV item." I said it can be any symbol.
This works for "This is !IV item." It fails for "This is _IV_ item though."
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.
2

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");

Comments

2

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

2 Comments

+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.
I think you meant (?<=\ )IV(?=\ ). Anyway, the OP said the surrounding characters could be anything other than ASCII letters and digits, not just spaces.

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.