1. Judging function
Public boolean matches of the String class (string regex)
Demand:
Determine if the mobile phone number meets the requirements?
Analysis:
A: Keyboard input mobile phone number
B: Rules for defining mobile numbers
13688886868
13866668888
13456789012
18638833883
C: Call function, Judge can
D: Output Results
1 ImportJava.util.Scanner;2 Public classRegexdemo {3 Public Static voidMain (string[] args) {4 //Keyboard Entry mobile phone number5Scanner sc =NewScanner (system.in);6System.out.println ("Please enter your mobile phone number:");7String phone =sc.nextline ();8 9 //rules for defining mobile numbersTenString regex = "1[38]\\d{9}"; One //1: The first character is 1,[38]: The second character is 3-8;//D{9}: The following 9 characters can be as long as the number is A - //call function, Judge can - BooleanFlag =phone.matches (regex); the - //Output Results -System.out.println ("flag:" +flag); - } +}
2, check the mailbox
Analysis:
Rules for mailbox:
1, (an indefinite number of letters or numbers) @ (2-4 indefinite number of letters or numbers). (COM/CN 2 or 3 letters) of which. (COM/CN) is an indefinite number of
2. Regular expression: String regx = "\\[email protected]\\w{2,6} (\.[ a-za-z]{2,3}) + ";
Analytical:
\\w: all letters and numbers; +: The front appears 1 or more times; \\w{2,6}: \\w can only show 2-6
\. : ‘.’ this character; [A-za-z]: all the letters; {2,3}: There are only 2-3 letters in front,
(\. [A-za-z] {2,3}) +: ' + ' before content appears 1 or more times
Attention:
A: yes \ not/
B: Regular expressions cannot have spaces
3, call the function of 2, to judge
Judging function
Public boolean matches of the String class (string regex)
4. Output Boolean type
1 ImportJava.util.Scanner;2 Public classEmailtest {3 4 Public Static voidMain (string[] args) {5 //Create keyboard Entry6Scanner sc =NewScanner (system.in);7System.out.println ("Please enter your email address:");8String str =sc.nextline ();9 Ten //define the composition of the mailbox OneString regex = "\\[email protected]\\w{2,6} (\\.\\w{2,3}) +"; A - //invoke the public boolean matches (string regex) of the function string class - BooleanFlag =str.matches (regex); the -SYSTEM.OUT.PRINTLN ("The email you entered is:" +flag); - } -}
Example of a Java 14-2 regular expression