Priyank Bolia
Priyank Bolia

Reputation: 14441

Need help in Regex Replace C#

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.

Upvotes: 1

Views: 265

Answers (3)

Matthias
Matthias

Reputation: 12259

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

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838716

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

Upvotes: 2

Pent Ploompuu
Pent Ploompuu

Reputation: 5414

Regex.Replace("This is IV item.", @"\bIV\b", "fourth");

Upvotes: 5

Related Questions