简体   繁体   English

用正则表达式匹配整个句子

[英]match whole sentence with regex

I'm trying to match sentences without capital letters with regex in Java: 我正在尝试用Java将正则表达式匹配不包含大写字母的句子:

"Hi this is a test" -> Shouldn't match
"hi thiS is a test" -> Shouldn't match
"hi this is a test" -> Should match

I've tried the following regex, but it also matches my second example ("hi, thiS is a test"). 我尝试了以下正则表达式,但它也与第二个示例匹配(“嗨,这是一个测试”)。

[a-z]+

It seems like it's only looking at the first word of the sentence. 似乎只看句子的第一个单词。

Any help? 有什么帮助吗?

[az]+ will match if your string contains any lowercase letter. 如果您的字符串包含任何小写字母,则[az]+将匹配。

If you want to make sure your string doesn't contain uppercase letters, you could use a negative character class: ^[^AZ]+$ 如果要确保您的字符串不包含大写字母,则可以使用负字符类: ^[^AZ]+$

Be aware that this won't handle accentuated characters (like É) though. 请注意,尽管如此,它不能处理强调字符(例如É)。

To make this work, you can use Unicode properties: ^\\P{Lu}+$ 为此,您可以使用Unicode属性: ^\\P{Lu}+$
\\P means is not in Unicode category , and Lu is the uppercase letter that has a lowercase variant category. \\P表示不在Unicode类别中 ,而Lu具有小写变体类别的大写字母

^[a-z ]+$

试试这个,这将验证正确的选择。

It's not matching because you haven't used a space in the match pattern, so your regex is only matching whole words with no spaces. 它不匹配,因为您没有在匹配模式中使用空格,因此您的正则表达式仅匹配没有空格的整个单词。

try something like ^[az ]+$ instead (notice the space is the square brackets) you can also use \\s which is shorthand for 'whitespace characters' but this can also include things like line feeds and carriage returns so just be aware. 尝试使用类似^[az ]+$ (注意空格是方括号),您也可以使用\\s ,它是“空白字符”的简写形式,但是它也可能包含换行符和回车符,因此请注意。

This pattern does the following: 此模式执行以下操作:

^ matches the start of a string ^匹配字符串的开头

[az ]+ matches any az character or a space, where 1 or more exists. [az ]+匹配任何a字符或空格(其中存在1个或多个)。

$ matches the end of the string. $匹配字符串的结尾。

I would actually advise against regex in this case, since you don't seem to employ extended characters. 在这种情况下,我实际上建议不要使用正则表达式,因为您似乎没有使用扩展字符。

Instead try to test as following: 而是尝试进行如下测试:

myString.equals(myString.toLowerCase());

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

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