Regular expression:
Essentially a schema that describes a set of strings that share that schemaRegular expression syntax:
characterx character
\\ backslash character
\t tab character
\n newline character
\r carriage return
character class:
[abc] a, b or c (simple class)
[^abc] any character except a, b or c (negation)
[a-zA-Z] a to z or A to Z, both inclusive (range)
Predefined character classes:
. Any character if it is itself.
\d Number: [0-9]
\ w word character: [a-zA-Z_0-9]: uppercase and lowercase letters, number character
boundary matcher:
^ start of line
$ end of line
\b end of word boundary (helloword?haha:world)
Greedy quantifier (emphasis)
X? X, one or no
X* X, zero or more
X+X, one or more
X{n} X characters occur exactly n times
X{n,} X characters appear at least n times
X{n, m} X characters appear at least n times, but not more than m times
Program example:
public static void main(String[] args) {Scanner sc = new Scanner(System.in) ;
System.out.println("Please enter a QQ number:");
String QQ =sc.nextLine() ;
boolean flag = checkQQ(QQ) ; //Call the regular expression
System.out.println(flag);
}
public static boolean checkQQ(String qq) {
return qq.matches("[1-9]\\d{4,14}" ) ; // The string method boolean matches(String regex) tells if this string matches the given regular expression.
}
Pattern class
The purpose is to create a matching pattern after compiling the regular expression.
String regex = "\\?|\\*";Pattern pattern = Pattern.compile(regex);
String patternStr = pattern.pattern();//返回\?\*
Matcher class
Match a regular expression using the pattern information provided by the Pattern instance
Pattern pattern = Pattern.compile("\\?{2}");Matcher matcher = pattern.matcher("??"); // Matcher matcher(String input) : Convert pattern object to matcher object
boolean matches = matcher.matches();
Two common methods in Pattern
String[] split(CharSequence input)
Splits the given input sequence around matches of this pattern.
String[] split(CharSequence input, int limit) The parameter limit is added to specify the number of segments to split by
splitting the given input sequence around matches of this pattern.