检查字符串是否包含列表中的数字,从字符串中删除该数字

时间:2018-04-09 19:59:58

标签: c# regex

我想检查字符串是否包含列表中的单词或数字,并将其从字符串中删除。

我想为找到的多个匹配执行此操作。

句子读出

  

这是01 02 03(01)(02)(03)no01 no02 no03 test

我需要Regex.Replace仅删除完整的010203,而不是其他字词。

  

这是(01)(02)(03)no01 no02 no03 test

但它只会删除所有地方03匹配项列表中最后一项的出现次数。

  

这是01 02(01)(02)()no01 no02 no test

http://rextester.com/BCEXTJ37204

C#

List<string> filters = new List<string>();
List<string> matches = new List<string>();

string sentence = "This is a 01 02 03 (01) (02) (03) no01 no02 no03 test";
string newSentence = string.Empty;

// Create Filters List
for (int i = 0; i < 101; i++)
{
    filters.Add(string.Format("{0:00}", i)); // 01-100
}

// Find Matches
for (int i = 0; i < filters.Count; i++)
{
    // Add to Matches List
    if (sentence.Contains(filters[i]))
    {
        matches.Add(filters[i]); // will be 01, 02, 03
    }
}

// Filter Sentence
for (int i = 0; i < matches.Count; i++)
{
    newSentence = Regex.Replace(sentence, matches[i], "", RegexOptions.IgnoreCase);
}

// Display New Sentence
Console.WriteLine(newSentence);

我尝试将string.Format()更改为@"\b{0:00}\b"以匹配整个单词,但它不起作用。

2 个答案:

答案 0 :(得分:1)

问题是您在原始字符串上重复调用正则表达式匹配器。这就是为什么只有最后一次改变“坚持”,而其他改变被抛弃:

newSentence = Regex.Replace(sentence, matches[i], "", RegexOptions.IgnoreCase);

如果您更改此选项以致电Replace上的newSentence,它将正常运行:

newSentence = sentence;
for (int i = 0; i < matches.Count; i++) {
    newSentence = Regex.Replace(newSentence, matches[i], "", RegexOptions.IgnoreCase);
}

但是,这不是最理想的:你最好将所有替换连接成一个正则表达式,如下所示:

newSentence = Regex.Replace(
    sentence
,   @"(?<=\s|^)(" + string.Join("|", matches) + @")(?=\s|$)"
,   ""
,   RegexOptions.IgnoreCase
);

您还可以删除构造filters的{​​{1}}的预检查,因为正则表达式引擎可以非常有效地处理它。

Demo.

答案 1 :(得分:1)

在代码中试用这个正则表达式:

     string sentence = "This is a 01 02 03 (01) (02) (03) no01 no02 no03 test";
     var newSentence = Regex.Replace(sentence, @"\s\d+(?=\s)", string.Empty);

     // Display New Sentence
     Console.WriteLine(newSentence);