简体   繁体   中英

Regex return line if it contains all letters and only 2 upper case in the whole string

I am calling a function to determine if the input string only contains 2 words all made up of only letters . That works fine. So 'suite 123' would fail and 'maddie girl' will pass. However, I need to make sure that consecutive uppercase letters will not pass such as 'AAA Bird' I only want to allow two uppercase in that whole string. Below is what I have at the moment. Any advise would be appreciated. I am very new to regex.

else if (line.matches("\\s*[A-Za-z]+\\s+[A-Za-z]+\\s*"))
        {
            getName();
        } 

You could use this regex:

^(?!(.*[A-Z]){3,})[a-zA-Z]+ [a-zA-Z]+$

It uses a negative lookahead to ensure that there are no more than 2 uppercase characters in the string, and then matches on a sequence of letters, followed by a space, followed by another sequence of letters.

Demo on regex101

我建议此正则表达式用于unicode字母:

^(?!(?:.*\p{Lu}){3,})\p{L}+\p{Zs}\p{L}+$

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