Hug*_*ron 13 .net c# regex string replace
I have a List of words I want to ignore like this one :
public List<String> ignoreList = new List<String>()
{
"North",
"South",
"East",
"West"
};
Run Code Online (Sandbox Code Playgroud)
For a given string, say "14th Avenue North" I want to be able to remove the "North" part, so basically a function that would return "14th Avenue " when called.
我觉得有一些东西我可以用LINQ,正则表达式和替换混合,但我只是想不出来.
更大的图景是,我正在尝试编写一个地址匹配算法.在使用Levenshtein算法评估相似性之前,我想过滤掉"Street","North","Boulevard"等词.
Gab*_*abe 13
这个怎么样:
string.Join(" ", text.Split().Where(w => !ignoreList.Contains(w)));
Run Code Online (Sandbox Code Playgroud)
或.Net 3:
string.Join(" ", text.Split().Where(w => !ignoreList.Contains(w)).ToArray());
Run Code Online (Sandbox Code Playgroud)
请注意,此方法将字符串拆分为单个单词,因此它只删除整个单词.这样,它会与地址一样正常工作,Northampton Way #123即string.Replace无法处理.
Regex r = new Regex(string.Join("|", ignoreList.Select(s => Regex.Escape(s)).ToArray()));
string s = "14th Avenue North";
s = r.Replace(s, string.Empty);
Run Code Online (Sandbox Code Playgroud)
这样的事情应该工作:
string FilterAllValuesFromIgnoreList(string someStringToFilter)
{
return ignoreList.Aggregate(someStringToFilter, (str, filter)=>str.Replace(filter, ""));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16892 次 |
| 最近记录: |