Java Regular Expressions
Java provides a powerful regular expression API, which is in the java. util. regex package. This tutorial describes how to use the regular expression API.
Regular Expression
A regular expression is a text pattern used for text search. In other words, the search mode appears in the text. For example, you can use a regular expression to search for email addresses or hyperlinks in a webpage.
Regular Expression example
The following is an example of a simple Java regular expression used to search for http ://
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String pattern = ".*http://.*";boolean matches = Pattern.matches(pattern, text);System.out.println("matches = " + matches);
The sample code does not actually detect whether the http: // found is part of a valid hyperlink, such as a domain name and suffix (. com,. net, etc ). The code is just a simple query string for http.
API for regular expressions in Java 6
This tutorial introduces the regular expression API in Java 6.
Pattern (java. util. regex. Pattern)
Class java. util. regex. Pattern (Pattern) is the main entry in the Java Regular Expression API. At any time, you must use a regular expression, starting from the Pattern class.
Pattern. matches ()
The most direct method to check whether a regular expression Pattern matches a piece of text is to call the static method Pattern. matches (), for example:
String text = "This is the text to be searched " + "for occurrences of the pattern.";String pattern = ".*is.*";boolean matches = Pattern.matches(pattern, text);System.out.println("matches = " + matches);
The code above finds whether the word "is" appears in the text variable, and allows "is" to contain 0 or more characters (specified)
The Pattern. matches () method is applicable to checking the occurrence of a Pattern in a text, or to the default settings of the Pattern class.
If you need to match multiple times, or even output different matching texts, or you only need to set it to a non-default setting. You must use the Pattern. compile () method to obtain a Pattern instance.
Pattern. compile ()
To match a regular expression multiple times in the text, you must use the Pattern. compile () method to create a Pattern object. Example:
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String patternString = ".*http://.*";Pattern pattern = Pattern.compile(patternString);
You can specify a special flag in the Compile method:
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
The Pattern class contains multiple signs (int type) that can control Pattern matching. The flag in the above Code makes pattern matching case-insensitive.
Pattern. matcher ()
Once the Pattern object is obtained, the Matcher object can be obtained. The Matcher example is used to match the pattern in the text. The example is as follows:
Matcher matcher = pattern.matcher(text);
The Matcher class has a matches () method to check whether the text matches the pattern. The following is a complete example of Matcher.
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String patternString = ".*http://.*";Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(text);boolean matches = matcher.matches();System.out.println("matches = " + matches);Pattern. split ()
The split () method of the Pattern class. The regular expression can be used as the separator to split the text into String-type arrays. Example:
String text = "A sep Text sep With sep Many sep Separators";String patternString = "sep";Pattern pattern = Pattern.compile(patternString);String[] split = pattern.split(text);System.out.println("split.length = " + split.length);for(String element : split){ System.out.println("element = " + element);}
In the preceding example, text is split into an array containing five strings.
Pattern. pattern ()
Returns the regular expression used to create a Pattern object. For example:
String patternString = "sep";Pattern pattern = Pattern.compile(patternString);String pattern2 = pattern.pattern();
In the code above, the pattern2 value is sep, which is the same as the patternString variable.
Matcher (java. util. regex. Matcher)
The java. util. regex. Matcher class is used to match a regular expression that appears multiple times in a piece of text. Matcher is also applicable to matching the same Regular Expression in multiple texts.
Matcher has many useful methods. For details, refer to the official JavaDoc. Here we will only introduce the core methods.
The following code demonstrates how to use Matcher
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String patternString = ".*http://.*";Pattern pattern = Pattern.compile(patternString);Matcher matcher = pattern.matcher(text);boolean matches = matcher.matches();
Create a Pattern, get Matcher, call the matches () method, and return true to indicate Pattern matching, and return false to indicate non-matching.
You can use Matcher to do more things.
Create Matcher
Create a matcher using the Matcher () method of Pattern.
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String patternString = ".*http://.*";Pattern pattern = Pattern.compile(patternString);Matcher matcher = pattern.matcher(text);
Matches ()
The matches () method of the Matcher class is used to match regular expressions in the text.
boolean matches = matcher.matches();
If the text matches the regular expression, the matches () method returns true. Otherwise, false is returned.
The matches () method cannot be used to find regular expressions that appear multiple times. If necessary, use the find (), start (), and end () methods.
LookingAt ()
The lookingAt () method is similar to the matches () method. The biggest difference is that the lookingAt () method matches the regular expression at the beginning of the text.
Matches () matches the regular expression for the entire text. In other words, if the regular expression matches the beginning of the text but does not match the entire text, lookingAt () returns true, while matches () returns false. Example:
String text = "This is the text to be searched " + "for occurrences of the http:// pattern.";String patternString = "This is the";Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(text);System.out.println("lookingAt = " + matcher.lookingAt());System.out.println("matches = " + matcher.matches());
In the above example, the regular expression "this is the" is matched for the beginning of the text and the entire text respectively. the method that matches the beginning of the text (lookingAt () returns true.
Returns false for the method (matches () that matches the regular expression of the entire text. Because the entire text contains redundant characters, the regular expression requires exact match of "this is ", there cannot be any additional characters before and after.
Find () + start () + end ()
The find () method is used to find the regular expression that appears in the text. When a Matcher is created, it is passed in by the Pattern. matcher (text) method. If multiple matches are found in the text, the find () method returns the first one, and the next one is returned every time you call find.
Start () and end () return the start and end positions of each matched string in the entire text. In fact, end () returns the last digit at the end of the String. In this way, the return values of start () and end () can be directly used in String. substring.
String text = "This is the text which is to be searched " + "for occurrences of the word 'is'.";String patternString = "is";Pattern pattern = Pattern.compile(patternString);Matcher matcher = pattern.matcher(text);int count = 0;while(matcher.find()) { count++; System.out.println("found: " + count + " : " + matcher.start() + " - " + matcher.end());}
In this example, the "is" mode is found four times in the text, and the output is as follows:
found: 1 : 2 - 4 found: 2 : 5 - 7 found: 3 : 23 - 25 found: 4 : 70 - 72
Reset ()
The reset () method resets the matching status inside the Matcher. When the find () method starts matching, Matcher internally records the distance to the current search. Calling reset () will re-search from the beginning of the text.
You can also call the reset (CharSequence) method. This method resets Matcher and uses a new string as a parameter to replace the original Matcher string.
Group ()
Assume that you want to search for URL links in a text file and extract the links. Of course, you can use the start () and end () methods. However, it is easier to use the group () method.
Grouping is represented in parentheses in a regular expression, for example:
(John)
This regular expression matches John, and parentheses do not belong to the text to be matched. Brackets define a group. When the regular expression matches the text, you can access the part in the group.
Use the group (int groupNo) method to access a group. A regular expression can have multiple groups. Each group is marked with a pair of parentheses. To access the text matched by a group in a regular expression, you can pass the group number to the group (int groupNo) method.
Group (0) indicates the entire regular expression. To obtain a group marked with parentheses, the group number should start from 1.
String text = "John writes about this, and John writes about that," + " and John writes about everything. " ;String patternString1 = "(John)";Pattern pattern = Pattern.compile(patternString1);Matcher matcher = pattern.matcher(text);while(matcher.find()) { System.out.println("found: " + matcher.group(1));}
The above code searches for the word John in the text. extract group 1 from each matching text, which is the part marked by parentheses. Output:
found: John found: John found: John
Multiple groups
As mentioned above, a regular expression can have multiple groups, for example:
(John) (.+?)
This expression matches the text "John" with a space, followed by one or more characters, and followed by a space. You may not see the last space.
This expression contains some special characters. Character point. represents any character. Character + indicates the occurrence of one or more characters. The combination of "and". "indicates any character and appears once or multiple times. Character? Indicates matching the text as short as possible.
The complete code is as follows:
String text = "John writes about this, and John Doe writes about that," + " and John Wayne writes about everything." ;String patternString1 = "(John) (.+?) ";Pattern pattern = Pattern.compile(patternString1);Matcher matcher = pattern.matcher(text);while(matcher.find()) { System.out.println("found: " + matcher.group(1) + " " + matcher.group(2));}
Pay attention to the way the group is referenced in the code. The code output is as follows:
found: John writes found: John Doe found: John Wayne
Nested Group
Groups can be nested in regular expressions, such
((John) (.+?))
This is the previous example, which is now placed in a large group. (There is a space at the end of the expression ).
When a nested group is encountered, the group number is determined by the order of left brackets. In the preceding example, group 1 is the big group. Group 2 is a group that includes John, and group 3 is a group that includes. +? . This is important when you need to reference a group through groups (int groupNo.
The following code demonstrates how to use nested groups
String text = "John writes about this, and John Doe writes about that," + " and John Wayne writes about everything." ;String patternString1 = "((John) (.+?)) ";Pattern pattern = Pattern.compile(patternString1);Matcher matcher = pattern.matcher(text);while(matcher.find()) { System.out.println("found: ");}
Output:
found: found: found:
ReplaceAll () + replaceFirst ()
The replaceAll () and replaceFirst () methods can be used to replace part of the Matcher search string. ReplaceAll () replaces all matching regular expressions, while replaceFirst () replaces only the first matching.
Before processing, Matcher will reset it first. Therefore, the matching expression starts from the beginning of the text.
Example:
String text = "John writes about this, and John Doe writes about that," + " and John Wayne writes about everything." ;String patternString1 = "((John) (.+?)) ";Pattern pattern = Pattern.compile(patternString1);Matcher matcher = pattern.matcher(text);String replaceAll = matcher.replaceAll("Joe Blocks ");System.out.println("replaceAll = " + replaceAll);String replaceFirst = matcher.replaceFirst("Joe Blocks ");System.out.println("replaceFirst = " + replaceFirst);
Output:
replaceAll = Joe Blocks about this, and Joe Blocks writes about that,and Joe Blocks writes about everything.replaceFirst = Joe Blocks about this, and John Doe writes about that,and John Wayne writes about everything.
The line breaks and indentation in the output are added for readability.
Note that all the places in the 1st string that contain John followed by a word are replaced with Joe Blocks. Of the 2nd strings, only the first one is replaced.
AppendReplacement () + appendTail ()
The appendReplacement () and appendTail () methods are used to replace the string phrase in the input text and append the replaced string to a StringBuffer.
When the find () method finds a matching item, you can call the appendReplacement () method, which causes the input string to be added to the StringBuffer and the matching text to be replaced. Starting from the end of the last matched text until the matched text is copied.
AppendReplacement () records the content in StringBuffer and can call find () until no matching item exists.
Until the last match item, the remaining part of the input text is not copied to StringBuffer. The text is from the end of the last match item to the end of the text. You can copy this part of content to StringBuffer by calling the appendTail () method.
String text = "John writes about this, and John Doe writes about that," + " and John Wayne writes about everything." ;String patternString1 = "((John) (.+?)) ";Pattern pattern = Pattern.compile(patternString1);Matcher matcher = pattern.matcher(text);StringBuffer stringBuffer = new StringBuffer();while(matcher.find()){ matcher.appendReplacement(stringBuffer, "Joe Blocks "); System.out.println(stringBuffer.toString());}matcher.appendTail(stringBuffer);System.out.println(stringBuffer.toString());
Note that the appendReplacement () method is called in the while loop. Call appendTail () after the loop is completed (). The code output is as follows:
Joe Blocks Joe Blocks about this, and Joe Blocks Joe Blocks about this, and Joe Blocks writes about that, and Joe Blocks Joe Blocks about this, and Joe Blocks writes about that, and Joe Blocks writes about everything.
Java regular expression syntax
To use regular expressions more effectively, you need to understand the regular expression syntax. The regular expression syntax is complex and can be used to write very advanced expressions. These grammar rules can be mastered only through a large number of exercises.
This article describes the basics of regular expression syntax through examples. The focus of the introduction will be on the core concepts that need to be understood to use regular expressions, without involving too much details. For more information, see the Pattern class in Java DOC.
Basic syntax
Before introducing advanced functions, we can quickly browse the basic syntax of regular expressions.
Character
It is the most frequently used expression in regular expressions. It is used to simply match a definite character. For example:
John
This simple expression will match John text in an input text.
You can use any English character in an expression. You can also use the octal, hexadecimal, or unicode encoding of character pairs. For example:
101
\x41
\u0041
All three expressions are uppercase letters. The first is octal encoding (101), the second is hexadecimal encoding (41), and the third is unicode encoding (2nd ).
Character Classification
Character classification is a structure that can match multiple characters, not just one character. In other words, a character category matches one character in the input text, and multiple Allowed characters are allowed in the corresponding character category. For example, if you want to match characters a, B, or c, the expression is as follows:
[abc]
[] Represents the character classification with a pair of square brackets. Square brackets are not part of matching.
Many tasks can be done by character classification. For example, to match the word John, the first letter can be uppercase or lowercase J.
[Jj]ohn
Character classification [Jj] matches J or j, and the remaining ohn matches the character ohn accurately.
Pre-defined character Classification
Regular expressions have predefined character types that can be used. For example, \ d represents any number, \ s represents any blank characters, and \ w represents any word characters.
Pre-defined character categories do not need to be enclosed in square brackets. Of course, they can also be used in combination.
\d
[\d\s]
1st match any number, and 2nd match any number or blank space.
The complete list of pre-defined character categories is listed at the end of this article.
Boundary match
Regular Expressions support matching boundaries, such as word boundaries, beginning or end of a text. For example, \ w matches a word, ^ matches the beginning of a row, and $ matches the end of a row.
^This is a single line$
The above expression matches a line of text, only the text This is a single line. Note that the beginning and end of a line are not followed by any text, but only the beginning and end of a line.
The complete list of matched boundaries is listed at the end of this article.
Quantifiers matching
A quantizer can match an expression multiple times. For example, the following expression matches letter A 0 or multiple times.
A*
The quantizer * Indicates 0 times or multiple times. + Indicates one or more times .? Indicates 0 or 1 time. For more quantifiers, see the list below.
Quantifiers are divided into hunger, greedy, and exclusive modes. Hunger mode matches as few texts as possible. Greedy mode matches as many texts as possible. The exclusive mode matches as many texts as possible, and even causes the matching of the remaining expressions to fail.
The following shows the differences between the hunger mode, greedy mode, and exclusive mode. Assume the following text:
John went for a walk, and John fell down, and John hurt his knee.
Expression in hunger mode:
John.*?
This expression matches John with 0 or more characters. . Represents any character. * Indicates 0 or multiple times .? Follow * to indicate that * adopts the hunger mode.
In hunger mode, quantifiers only match as few characters as possible, that is, 0 characters. In the preceding example, the expression matches the word John and appears three times in the input text.
If the greedy mode is changed, the expression is as follows:
John.*
In greedy mode, quantifiers match as many characters as possible. Now the expression matches the first occurrence of John and all the remaining characters in greedy mode. In this way, there is only one matching item.
Finally, we changed to the exclusive mode:
John.*+hurt
* Followed by + indicates the exclusive mode quantizer.
This expression does not match in the input text, although the text contains John and hurt. Why? Because. * + is an exclusive mode. In greedy mode, match as many texts as possible to make the entire expression match differently. The exclusive mode will match as much as possible, but does not consider whether the remaining part of the expression can match.
. * + Will match all characters after the first John, which causes no match for the remaining hurts in the expression. If it is changed to greedy mode, there will be a match. The expression is as follows:
John.*hurt
Logical operators
Regular Expressions support a small number of logical operations (and, or, not ).
And the operation is the default, expression John, meaning J and o and h and n.
Or the operation needs to be displayed and specified, represented by |. For example, the expression John | hurt means John or hurt.
Character character Classification
Built-in character classification boundary match
Quantifiers
I have a public account that will often share some Java-related things. If you like it, you can search for "Java headers" or "javatuanzhang.
Refer:
- Java Regular Expression | cainiao tutorial
- Java regular expression syntax and example
- JAVA Regular Expression (ultra-detailed)