简体   繁体   English

如何在空格上匹配正则表并在不覆盖空格的情况下进行替换

[英]How to Regex match on spaces and replace without overwriting spaces

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". 所以“这是一个特别的1句话”将成为“这是一个特殊的句子”。 With the Replace statement above I get "This is aspecial1sentence". 使用上面的替换语句,我得到“这是aspecial1sentence”。

Solution: 解:

Based on @Jerry's comment, I changed the match to: 基于@Jerry的评论,我将比赛更改为:

(\\\\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. 并且能够获得理想的结果。

You can use a lookbehind and a lookahead to check for the spaces without including them in the match: 您可以使用lookbehind和lookahead检查空格,而不在匹配中包含它们:

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. 这样您就不必再添加空格了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM