简体   繁体   中英

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. 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]+ Match an uppercase char AZ and 1+ lowercase chars 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}+$

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

True
False
False
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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