如何使用regexp查找字符串中的模式?

时间:2016-07-11 14:31:26

标签: c#

我有很多模式想要在许多字符串数组中找到匹配的字符串,并将其替换为" NON"串。 例如,如果我们有:

str[0]={"this","is","a simple","text","for","example","."};
str[1]={"Can","you","help me","please","?","thank","you","very much"};
string[] patterns={"the","that","(eg width)","123",",","text","for example","help me","very much"};

将str [i]中的匹配模式替换为" NON"是欲望的结果:

str[0]={"this","is","a simple","NON","NON","NON","."};
str[1]={"Can","you","NON","please","?","thank","you","NON"};`

我该怎么做?

感谢。

2 个答案:

答案 0 :(得分:0)

如果你想要一个变异的解决方案:

public void ReplaceStrs(string[] srcStrs, string[] patterns, string changeTo)
{
    for (int i=0; i < srcStrs; i++) {
        if (Array.IndexOf(patterns, toChange[i]) >= 0) {
            srcStrs[i] = changeTo;
        }
    }
}

非不同诱变:

public string[] ReplaceStrs(string[] srcStrs, string[] patterns, string changeTo) {
     srcStrs.Select(s => Array.IndexOf(patterns, s) >= 0 ? changeTo : s).ToArray();
}

答案 1 :(得分:0)

只是为了好玩的一个班轮:]

str = Array.ConvertAll(str, a => Array.ConvertAll(a, i => patterns.Contains(i) ? "NON" : i));