正则表达式仅限制大写 [英] Regex to restrict UPPERCASE only
问题描述
我仍在努力理解 Regex 的工作原理.
I am stil struggling with understanding how Regex works exactly.
我正在获取用户名,它们采用以下格式:
I am getting usernames and they are in this format:
firstname.lastname
两个名称都可能包含特殊的国际字符,并且可能包含一个 ' 或 - 但我只需要检测它们是否包含任何大写字母,以便我可以抛出异常.
Both names may contain special international characters and they may contain an ' or - but I just need to detect if they contain any uppercase letters so I can throw an exception.
我正在使用这个表达
[^A-Z].[^A-Z]
在我看来这应该有效,我只是不明白为什么它不起作用.
It seems to me that this should work, I just don't understand why it doesn't.
希望有人能解释一下.
谢谢!
推荐答案
[^A-Z]
仅表示不是大写 A 到大写 Z 的任何字符.
[^A-Z]
Simply means any character that isn't a capital A through capital Z.
.
表示您应该使用的任何字符 \.
因为这表示文字字符 .
.
Means any character you should be using \.
As this means the literal character .
一个字符组是[]
,反面是[^]
然后把你想匹配的字符放进去.
A character group is []
and the inverse is [^]
you then put the characters you want to match.
但是,您的正则表达式看起来只会匹配一个不是大写字母的字符,然后是任何字符,然后是另一个不是大写字母的单个字符
However, your regex looks like it will match only a single character that isn't a capital letter then any character then another single character that isn't a capital letter
您要使用以下内容:
[^A-Z]+\.[^A-Z]+
正则表达式中的 +
表示匹配前面提到的 1 到无限次.
The +
in regex means match the before stated 1 to infinite times.
如果你只想要这个文本而不是其他文本,你应该包含行首和行尾标签,这样它就不会匹配包含你提到的格式的长字符串.
If you are only going to have this text and no other text you should include the start of line and end of line tag so that it doesn't match long strings that include something formatted like you mentioned.
但是,您的正则表达式也匹配空格和制表符.
However, your regex does also match spaces and tabs.
所以我会使用以下内容:
^[^A-Z\s]+\.[^A-Z\s]+$
这篇关于正则表达式仅限制大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!