Analysis of a regular expression that matches numbers and letters and passwords
The password for a user registration function must consist of numbers and letters. It must contain both numbers and letters and be between 8 and 16 characters in length.
How to analyze requirements? Split! This is the general idea of software design. Therefore, the splitting requirement is as follows:
1. Not all numbers
2. Not all letters
3. It must be a number or letter.
As long as the above three requirements can be met at the same time, it is written as follows:
^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$
Separate the following comments:
^ Match the starting position of a row
(?! [0-9] + $) predicting that the position is not followed by all numbers
(?! [A-zA-Z] + $) predict that the position is not followed by all letters
[0-9A-Za-z] {8, 16} consists of 8-16 digits or the letter
$ Match the end of a row
Note :(?! Xxxx) is a form of assertion of a regular expression with a negative and Zero Width. It indicates that the pre-location is not a xxxx character.
The test cases are as follows:
Public class Test {public static void main (String [] args) throws Exception {String regex = "^ (?! [0-9] + $ )(?! [A-zA-Z] + $) [0-9A-Za-z] {8, 16} $ "; String value =" aaa "; // The length is insufficient for System. out. println (value. matches (regex); value = "1111aa1111aaaaa"; // too long System. out. println (value. matches (regex); value = "111111111"; // pure number System. out. println (value. matches (regex); value = "aaaaaaaaa"; // pure Letter System. out. println (value. matches (regex); value = "######"; // special character System. out. println (value. matches (regex); value = "1111 aaaa"; // a combination of numbers and letters: System. out. println (value. matches (regex); value = "aaaa1111"; // a combination of numbers and letters: System. out. println (value. matches (regex); value = "aa1111aa"; // a combination of numbers and letters: System. out. println (value. matches (regex); value = "11aaaa11"; // a combination of numbers and letters: System. out. println (value. matches (regex); value = "aa11aa11"; // a combination of numbers and letters: System. out. println (value. matches (regex ));}}
The above is a regular expression that matches numbers and letters and passwords. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!