【问题标题】:Regex to check for two words containing only letters in a sentence正则表达式检查句子中仅包含字母的两个单词
【发布时间】:2021-08-23 21:46:11
【问题描述】:

这会检查两个单词,但如果单词包含数字,也会返回 true。那么,如何使用此正则表达式检查句子中仅包含字母的两个单词?

Regex.IsMatch(alphabets, @"^((?:\S+\s+){2}\S+).*");
//should return true if string is Honda Civic
//should return false if string is Honda Civic TypeR
//should return false if string is H56da Civic 
//should return false if string is Honda

【问题讨论】:

    标签: c# regex boolean


    【解决方案1】:

    你可以使用

    ^[A-Z][a-z]+\s+[A-Z][a-z]+$
    
    • ^ 字符串开始
    • [A-Z][a-z]+\s+ 匹配一个大写字符 A-Z、1+ 个小写字符 a-z 和 1+ 个空白字符
    • [A-Z][a-z]+ 匹配一个大写字符 A-Z 和 1+ 个小写字符 a-z
    • $字符串结束

    Regex demo

    或者更广泛一点,其中\p{Lu} 匹配具有小写变体的大写字母,p{Ll} 匹配具有大写变体的小写字母,[\p{Zs}\t] 匹配空白字符或制表符。

    ^\p{Lu}\p{Ll}+[\p{Zs}\t]+\p{Lu}\p{Ll}+$
    

    例子

    string[] strings = { 
        "Honda Civic",
        "Civic TypeR",
        "H56da Civic",
        "Honda"
        };
    foreach (String alphabets in strings) {
        Console.WriteLine(Regex.IsMatch(alphabets, @"^[A-Z][a-z]+\s+[A-Z][a-z]+$"));
    }
    

    输出

    True
    False
    False
    False
    

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多