使用RegEx匹配相似的单词

时间:2012-08-12 05:05:49

标签: c# regex

大家好:我需要使用RexEx匹配相似的单词。例如,如果我有一个包含像“autonomous”这样的单词的模式,它应匹配单词“autonomy”而不匹配“autonomous”。
示例代码:

void modify(string word)
{
string input = "This island is a colony; however,it is autonomous and " + 
"receives no orders from the mother country, autonomy, N.";
string pattern = @",\s" + word + @"\s[v|n|adj]\.";//word = "autonomous";
Regex reg = new Regex(pattern);
string output = reg.Replace(input, ".");
}

2 个答案:

答案 0 :(得分:1)

我不确定你是否能够单独使用Regex轻松实现。

你应该看一下模式匹配算法。有a similar question here涵盖了这个主题。

答案 1 :(得分:1)

这可能是您正在寻找的:

string s= "This island is a colony; however,it is autonomous and receives no orders from the mother country, autonomy, N.";;
string pattern="autonomous";
Regex r=new Regex(@"\b(?!"+pattern+")"+pattern.Substring(0,pattern.Length/2)+@".*?\b");
r.Replace(s,".");