簡體   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