简体   繁体   English

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

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

This checks for two words but also returns true if words contains numbers.这会检查两个单词,但如果单词包含数字,也会返回 true。 So, How can I to check for two words containing only letters in a sentence with this Regex?那么,如何使用此正则表达式检查句子中仅包含字母的两个单词?

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

You can use您可以使用

^[A-Z][a-z]+\s+[A-Z][a-z]+$
  • ^ Start of string ^字符串开头
  • [AZ][az]+\s+ Match an uppercase char AZ, 1+ lowercase chars az and 1+ whitespace chars [AZ][az]+\s+匹配一个大写字符 AZ、1+ 个小写字符 az 和 1+ 个空白字符
  • [AZ][az]+ Match an uppercase char AZ and 1+ lowercase chars az [AZ][az]+匹配一个大写字符 AZ 和 1+ 个小写字符 az
  • $ End of string $字符串结尾

Regex demo正则表达式演示

Or a bit broader, where \p{Lu} matches an uppercase letter that has a lowercase variant, p{Ll} matches a lowercase letter that has an uppercase variant and [\p{Zs}\t] matches a whitespace char or a tab.或者更广泛一点,其中\p{Lu}匹配具有小写变体的大写字母, p{Ll}匹配具有大写变体的小写字母,而[\p{Zs}\t]匹配空白字符或标签。

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

Example例子

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 Output

True
False
False
False

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

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