First, the basic knowledge
A regular expression is a string of characters that describes a sequence of characters. This generic description is called a pattern and can be used to find matches in other character sequences. The regular expressions for Java consist of pattern and matcher, pattern is used to define regular expressions, and Matcher is used to match patterns in other sequences.
Second, the grammar
Regular expressions are composed of regular characters, character classes, wildcard characters, and quantifiers.
Regular characters are matched according to themselves.
A character class is a set of characters that can be specified by placing a character between square brackets.
Wildcard characters can match any character.
The quantifier determines how many times the expression will be matched.
| ^ |
Match the starting position of the input string |
| $ |
Match the end position of the input string |
| * |
Matches the preceding character or subexpression 0 or more times |
| + |
Match the preceding character or subexpression one or more times |
| ? |
Match the preceding character or subexpression 0 or one time |
| N |
Matches the preceding character or subexpression n times |
| {N,} |
Matches the preceding character or sub-expression at least n times |
| {N,m} |
Matches the preceding character or subexpression at least n times, up to M times |
| ? |
The match pattern after the qualifier is non-greedy and matches the shortest possible string. The default greedy pattern matches strings as long as possible. |
| a| B |
Match A or B |
| [ABC] |
Match any of the characters in ABC |
| [^ABC] |
Match any character that is not ABC |
| [A-z] |
Match any character within a-Z |
Iii. examples
ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;classSolution { Public Static voidMain (string[] args) {pattern pattern= Pattern.compile ("[a-z]+"); Matcher Matcher= Pattern.matcher ("Hello World"); System.out.println (Matcher.matches ());//do not match substringsMatcher.reset (); while(Matcher.find ()) {//matching substringsSystem.out.println (Matcher.start ());//gets the current matching start of the lead cableSystem.out.println (Matcher.end ());//Gets the end of the current matching cableSystem.out.println (Matcher.group ());//gets the last matching string} String Str= Matcher.replaceall (""); System.out.println (str); }}View Code
Splits a string.
Import java.util.Arrays; Import Java.util.regex.Pattern; class Solution { publicstaticvoid main (string[] args) { = Pattern.compile ("[,.!]" ); = Pattern.split ("jetbrains! Intellij,idea. " ); System.out.println (Arrays.tostring (strings));} }
View Code
Java notes: Regular expressions