我发现这段代码可以获取一个字符串的所有单词,
static string[] GetWords(string input)
{
MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b");
var words = from m in matches.Cast<Match>()
where !string.IsNullOrEmpty(m.Value)
select TrimSuffix(m.Value);
return words.ToArray();
}
static string TrimSuffix(string word)
{
int apostrapheLocation = word.IndexOf('\'');
if (apostrapheLocation != -1)
{
word = word.Substring(0, apostrapheLocation);
}
return word;
}
- 请描述一下代码。
- 如何得到没有数字的单词?
最佳答案
2 How can I get words without figures?
您必须将 \w
替换为 [A-Za-z]
这样你的正则表达式就变成了@"\b[A-Za-z']*\b"
然后您将不得不考虑 TrimSuffix()。 regEx 允许撇号,但 TrimSuffix() 将仅提取左侧部分。所以“它”会变成“它”。
关于c# - 使用 RegEx 查找所有没有数字的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5755029/