繁体   English   中英

正则表达式检查句子中仅包含字母的两个单词

[英]Regex to check for two words containing only letters in a sentence

这会检查两个单词,但如果单词包含数字,也会返回 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

您可以使用

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

正则表达式演示

或者更广泛一点,其中\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]+$"));
}

Output

True
False
False
False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM