c# - 使用 RegEx 查找所有没有数字的单词

标签 c# .net regex

我发现这段代码可以获取一个字符串的所有单词,

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;
}
  1. 请描述一下代码。
  2. 如何得到没有数字的单词?

最佳答案

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/

相关文章:

c# - 当参数之一为 void* 时,如何在 C# 中使用 C 函数?

c# - 为什么不使用 HashSet<T> 类来实现 Enumerable.Distinct

c# - 如何在调用 Task.WaitAll 之前了解异常?

javascript - 使用 Javascript 提取 a href 路径的一部分

python - 从 sql 模式文件中提取 Table Create 语句

C# - response.Content.ReadAsAsync<Result> 没有像我认为的那样工作

c# - 正则表达式与字符串操作函数 : What is better

c# - 通用存储库扩展 : Inheritance vs. 扩展方法

c# - NetworkStream.DataAvailable 属性在使用 SslStream 时不返回正确的结果

Javascript正则表达式如何实现?