且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否包含小写字母,大写字母,特殊字符和数字?

更新时间:2022-11-08 23:14:28

这可以在java中作为单个正则表达式执行,但我个人会使用类似Mark Rhodes提供的解决方案。这将变得荒谬快速(如果它还没有...)随着规则变得更多很复杂。

This does what you want in java as a single regex, although I would personally use something like the solution provided by Mark Rhodes. This will get ridiculous quick (if it isn't already...) as the rules get more complicated.

String regex = "^(?=.*?\\p{Lu})(?=.*?[\\p{L}&&[^\\p{Lu}]])(?=.*?\\d)" + 
               "(?=.*?[`~!@#$%^&*()\\-_=+\\\\\\|\\[{\\]};:'\",<.>/?]).*$"




  1. ^这匹配字符串的开头。这不是必须的,但我觉得它有助于提高可读性和理解力。此外,使用它时,通常可以大幅度提高性能并且几乎不会受到惩罚。

  1. ^ This matches the beginning of the string. It's not strictly necessary for this to work, but I find it helps readability and understanding. Also, using it when you can often makes a big performance improvement and is almost never a penalty.

(?= X )这被称为积极前瞻。基本上我们所说的是字符串的开头(^)必须跟着这个东西 X 才能匹配,但不要将光标前进到 X 的结尾,留在行的开头。(这是向前看部分。)

(?=X) This is called a positive lookahead. Basically what we're saying is "The beginning of the string (^) must be followed by this thing X in order for a match, but DO NOT advance the cursor to the end of X, stay at the beginning of the line. (that's the "look ahead" part.)

。* ?\p {Lu}在行开头之后吃字符,直到找到大写字母。如果没有找到大写字母,这将无法匹配。我们使用\p {Lu}而不是AZ,因为我们没有希望来自世界其他地方的人们举起手来抱怨我们的软件是如何由一个无知的美国人写的。

.*?\p{Lu} eat characters after the beginning of the line until you find a capital letter. This will fail to match if no capital letter is found. We use \p{Lu} instead of A-Z because we don't want people from other parts of the world to throw up their hands and complain about how our software was written by an ignorant American.

现在我们回到行的开头(我们回去因为我们使用了前瞻)并开始搜索。*?[\p {L}&& [^ \p {Lu}]]简写为所有字母,减去大写(因此匹配小写)。

Now we go back to the beginning of the line (we go back because we used lookahead) and start a search for .*?[\p{L}&&[^\p{Lu}]] shorthand for "all letters, minus the capitals" (hence matches lower case).

。*?\ d +。*?[`〜!@#$%^& *( )\ -_ = + \\\ | \ [{\]} ;:'\,&LT;> /?]重复数字和特殊字符列表。

.*?\d + .*?[`~!@#$%^&*()\-_=+\\\|\[{\]};:'\",<.>/?] repeat for digits and for your list of special characters.

。* $匹配其他所有内容,直到行尾。我们这样做只是因为java中'matches'方法的语义,看看整个字符串是否与正则表达式匹配。您可以保留这部分并使用Matcher#find()方法并获得相同的结果。

.*$ Match everything else until the end of the line. We do this just because of the semantics of the 'matches' methods in java that see if the entire string is a match for the regex. You could leave this part of and use the Matcher#find() method and get the same result.

猫头鹰是有史以来针对任何技术主题撰写的***的书籍之一。它简短快速阅读。我不能推荐它。

The Owl is one of the best books ever written on any technical subject. And it's short and fast to read. I cannot recommend it enough.