Reputation: 3122
I have a Regex match like the following code:
string[] specials = new string[] { "special1", "special2", "special3" };
for (int i = 0; i < specials.Length; i++)
{
string match = string.Format("(?:\\s)({0})(?:\\s)", specials[i]);
if (Regex.IsMatch(name, match, RegexOptions.IgnoreCase))
{
name = Regex.Replace(name, match, specials[i], RegexOptions.IgnoreCase);
break;
}
}
What I would like is to have the replace operation replace only the matching text and leave the leading and trailing space in tact. So "This is a Special1 sentence" would become "This is a special1 sentence". With the Replace statement above I get "This is aspecial1sentence".
Solution:
Based on @Jerry's comment, I changed the match to:
(\\s)({0})(\\s)
and the Replace to:
name = Regex.Replace(name, match, "$1" + specials[i] + "$3", RegexOptions.IgnoreCase);
and was able to get the desired results.
Upvotes: 0
Views: 177
Reputation: 574
You can use a lookbehind and a lookahead to check for the spaces without including them in the match:
string[] specials = new string[] { "special1", "special2", "special3" };
for (int i = 0; i < specials.Length; i++)
{
string match = string.Format("(?<=\\s){0}(?=\\s)", specials[i]);
if (Regex.IsMatch(name, match, RegexOptions.IgnoreCase))
{
name = Regex.Replace(name, match, specials[i], RegexOptions.IgnoreCase);
break;
}
}
This way you don't have to add the spaces back in.
Upvotes: 2