Java Regular Expressions

Source: Internet
Author: User

The regular expression defines the pattern of the string.
Regular expressions can be used to search, edit, or manipulate text.
Regular expressions are not limited to a single language, but have subtle differences in each language.
Java regular expressions are the most similar to Perl.
The Java.util.regex package mainly consists of the following three classes:

Pattern class:
The pattern object is a compiled representation of a regular expression. The pattern class has no public constructor method. To create a pattern object, you must first call its public static compilation method, which returns a Pattern object. The method takes a regular expression as its first argument.
Matcher class:
The Matcher object is the engine that interprets and matches the input string. Like the pattern class, Matcher does not have a public construction method. You need to invoke the Matcher method of the Pattern object to get a Matcher object.
patternsyntaxexception:
Patternsyntaxexception is a non-mandatory exception class that represents a syntax error in a regular expression pattern.

Capturing groups
A capturing group is a method of processing multiple characters as a single unit, which is created by grouping characters within parentheses.
For example, the regular expression (dog) creates a single group that contains "D", "O", and "G".
Capturing groups are numbered by calculating their opening brackets from left to right. For example, in an expression ((A) (B (C))), there are four such groups:
((A) (B (C)))
A
(B (C))
C
You can see how many groupings of an expression by calling the GroupCount method of the Matcher object. The GroupCount method returns an int value that indicates that the Matcher object currently has more than one capturing group.
There is also a special group (group 0), which always represents the entire expression. The group is not included in the return value of GroupCount.

Example
The following example shows how to find the number string from a given string:

Import Java.util.regex.matcher;import Java.util.regex.Pattern; Public classregexmatches{ Public Static void Main(String args[]) {//In string lookup by specified modeString line ="This order is placed for qt3000! Ok? "; String pattern ="(. *) (\\d+) (. *)";//Create Pattern ObjectPattern R = pattern.compile (pattern);//Create Matcher object nowMatcher m = r.matcher (line);if(M.find ()) {System. out. println ("Found value:"+ M.Group(0) ); System. out. println ("Found value:"+ M.Group(1) ); System. out. println ("Found value:"+ M.Group(2) ); }Else{System. out. println ("NO MATCH"); }   }}

The results of the above example compilation run as follows:

valueforvalueforvalue0

Regular expression syntax

character Description
\ Marks the next character as a special character, text, reverse reference, or octal escape. For example, "n" matches the character "n". "\ n" matches the line break. The sequence "\" matches "\", "(" Match "(".
^ Matches the starting position of the input string. If the Multiline property of the RegExp object is set, ^ will also match the position after "\ n" or "\ r".
$ Matches the position of the end of the input string. If you set the Multiline property of the RegExp object, the $ will also match the position before \ n or \ r.
* Matches the preceding character or sub-expression 0 or more times. For example, zo* matches "z" and "Zoo". * Equivalent to {0,}.
+ Matches the preceding character or sub-expression one or more times. For example, "zo+" matches "Zo" and "Zoo", but does not match "Z". + equivalent to {1,}.
? Matches the preceding character or sub-expression 0 or one time. For example, "Do (es)?" Match "Do" in "do" or "does".? Equivalent to {0,1}.
N N is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match "O" in "Bob", but matches two "o" in "food".
{N,} N is a non-negative integer. Match at least n times. For example, "o{2,}" does not match "O" in "Bob", but matches all o in "Foooood". "O{1,}" is equivalent to "o+". "O{0,}" is equivalent to "o*".
{N,m} M and n are non-negative integers, where n <= m. Matches at least n times, up to M times. For example, "o{1,3}" matches the first three o in "Fooooood". ' o{0,1} ' is equivalent to ' O? '. Note: You cannot insert a space between a comma and a number.
? When this character follows any other qualifier (*, + 、?、 {n}, {n,}, {n,m}), the matching pattern is "non-greedy". The "non-greedy" pattern matches the shortest possible string searched, while the default "greedy" pattern matches the string that is searched for as long as possible. For example, in the string "Oooo", "o+?" Only a single "O" is matched, and "o+" matches All "O".
. Matches any single character except for "\ r \ n". To match any character that includes "\ r \ n", use a pattern such as "[\s\s]".
(pattern) Matches the pattern and captures the matched sub-expression. can use 0 ... The 9 property retrieves a captured match from the result "match" collection. To match the bracket character (), use (or).
(?:p Attern) A subexpression that matches the pattern but does not capture the match, that is, it is a non-capturing match and does not store a match for later use. This is useful for combining pattern parts with the "or" character (|). For example, ' Industr (?: y|ies) is a more economical expression than ' industry|industries '.
(? =pattern) A subexpression that performs a forward lookahead search that matches the string at the starting point of the string that matches the pattern. It is a non-capture match, that is, a match that cannot be captured for later use. For example, ' Windows (? =95|98| nt|2000) ' Matches Windows 2000 ' in Windows, but does not match Windows 3.1 in Windows. Lookahead does not occupy characters, that is, when a match occurs, the next matching search immediately follows the previous match, rather than the word specifier that makes up the lookahead.
(?! Pattern A subexpression that performs a reverse lookahead search that matches a search string that is not at the starting point of a string that matches the pattern. It is a non-capture match, that is, a match that cannot be captured for later use. For example, ' Windows (?! 95|98| nt|2000) ' matches Windows 3.1 ' in Windows, but does not match Windows 2000 in Windows. Lookahead does not occupy characters, that is, when a match occurs, the next matching search immediately follows the previous match, rather than the word specifier that makes up the lookahead.
X|y Match x or Y. For example, ' Z|food ' matches ' z ' or ' food '. ' (z|f) Ood ' matches "Zood" or "food".
[XYZ] Character. Matches any one of the characters contained. For example, "[ABC]" matches "a" in "plain".
[^XYZ] The reverse character set. Matches any characters that are not contained. For example, "[^abc]" matches "plain" in "P", "L", "I", "N".
[A-z] The character range. Matches any character within the specified range. For example, "[A-z]" matches any lowercase letter in the range "a" to "Z".
[^a-z] The inverse range character. Matches any character that is not in the specified range. For example, "[^a-z]" matches any character that is not in the range "a" to "Z".
\b Matches a word boundary, which is the position between the word and the space. For example, "er\b" matches "er" in "never", but does not match "er" in "verb".
\b Non-word boundary match. "er\b" matches "er" in "verb", but does not match "er" in "Never".
\cx Matches the control character indicated by X. For example, \cm matches a control-m or carriage return character. The value of x must be between A-Z or a-Z. If this is not the case, then the C is assumed to be the "C" character itself.
\d numeric character matching. equivalent to [0-9].
\d Non-numeric character matching. equivalent to [^0-9].
\f The page break matches. Equivalent to \x0c and \CL.
\ n Line break matches. Equivalent to \x0a and \CJ.
\ r Matches a carriage return character. Equivalent to \x0d and \cm.
\s Matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v].
\s Matches any non-whitespace character. equivalent to [^ \f\n\r\t\v].
\ t TAB matches. Equivalent to \x09 and \ci.
\v Vertical tab matches. Equivalent to \x0b and \ck.
\w Matches any character, including underscores. Equivalent to "[a-za-z0-9_]".
\w Matches any non-word character. Equivalent to "[^a-za-z0-9_]".
\xn Match N, where N is a hexadecimal escape code. The hexadecimal escape code must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows the use of ASCII code in regular expressions.
\num Matches num, where num is a positive integer. To capture a matching reverse reference. For example, "(.) \1 "matches two consecutive identical characters.
\ n Identifies an octal escape code or a reverse reference. If there are at least N captured subexpression in front of it, then N is a reverse reference. Otherwise, if n is an octal number (0-7), then N is the octal escape code.
\nm Identifies an octal escape code or a reverse reference. If there is at least a NM capture subexpression in front of the \nm, then NM is a reverse reference. If there are at least N captures in front of the \nm, then n is a reverse reference followed by the character M. If neither of the preceding cases exists, then \nm matches the octal value nm, where N and M are octal digits (0-7).
\nml When n is an octal number (0-3), M and L are octal numbers (0-7), the octal escape code NML is matched.
\un Matches n, where N is a Unicode character represented by a four-bit hexadecimal number. For example, \u00a9 matches the copyright symbol (?).

methods of the Matcher class
Index Method
The index method provides useful index values that exactly indicate where the match is found in the input string:

Serial Number Method and Description
1 public int Start ()
Returns the initial index of the previous match.
2 public int start (int group)
Returns the initial index of a subsequence captured by a given group during a previous match operation
3 public int End ()
Returns the offset after the last matching character.
4 public int end (int group)
Returns the offset after the last character of a subsequence captured by a given group during a previous match operation.

Research Methods
The research method is used to check the input string and return a Boolean value indicating whether the pattern is found:

Serial Number Method and Description
1 public boolean Lookingat ()
Attempts to match the input sequence starting at the beginning of the zone with the pattern.
2 public Boolean find ()
Attempts to find the next subsequence of the input sequence that matches the pattern.
3 public boolean find (int start)
Resets the match and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.
4 public Boolean matches ()
Try to match the entire region to the pattern.

Replacement Method
The replacement method is the method of replacing the text in the input string:

Serial Number Method and Description
1 Public Matcher appendreplacement (StringBuffer SB, String replacement)
Implement non-terminal add and replace steps.
2 Public StringBuffer Appendtail (StringBuffer SB)
Implement terminal add and replace steps.
3 public string ReplaceAll (string replacement)
The replacement pattern matches each subsequence of the input sequence with the given replacement string.
4 public string Replacefirst (string replacement)
Replaces the first subsequence of an input sequence that matches a given replacement string.
5 public static string Quotereplacement (string s)
Returns the literal substitution string for the specified string. This method returns a string that works like a literal string passed to the Appendreplacement method of the Matcher class.

start and End methods
Here is an example of the count of occurrences of the word "cat" appearing in the input string:

Import Java.util.regex.matcher;import Java.util.regex.Pattern; Public classregexmatches{Private StaticFinal String REGEX ="\\bcat\\b";Private StaticFinal String INPUT ="Cat cat cat Cattie Cat"; Public Static void Main(String args[])       {Pattern p = pattern.compile (REGEX); Matcher m = P.matcher (INPUT);//Get Matcher object       intCount =0; while(M.find ())         {count++; System. out. println ("Match number"+count); System. out. println ("Start ():"+m.start ()); System. out. println ("End ():"+m.end ()); }   }}

The results of the above example compilation run as follows:

Match Number 1start  (): 0  end  (): 3  match  Span class= "Hljs-keyword" >number  2  start  (): 4  end  ():  7  match  number  3  start  (): 8  end  (): 11  match  number  4  start  (): 19  end  (): 22 

You can see that this example is using the word boundary to make sure that the letter "C" "a" "T" is not just a substring of a longer word. It also provides some useful information about where the match occurred in the input string.
The Start method returns the initial index of the subsequence captured by the given group during the previous match operation, and the end method indexes the last matching character plus 1.

matches and Lookingat methods
Both the matches and Lookingat methods are used to try to match an input sequence pattern. The difference is that Matcher requires that the entire sequence be matched, while Lookingat is not required.
These two methods are often used at the beginning of the input string.
Let's explain this feature in the following example:

Import Java.util.regex.matcher;import Java.util.regex.Pattern; Public classregexmatches{Private StaticFinal String REGEX ="foo";Private StaticFinal String INPUT ="Fooooooooooooooooo";Private StaticPattern pattern;Private StaticMatcher Matcher; Public Static void Main(String args[])       {pattern = Pattern.compile (REGEX);       Matcher = Pattern.matcher (INPUT); System. out. println ("Current REGEX is:"+regex); System. out. println ("Current INPUT is:"+input); System. out. println ("Lookingat ():"+matcher.lookingat ()); System. out. println ("matches ():"+matcher.matches ()); }}

The results of the above example compilation run as follows:

isistruefalse

Replacefirst and ReplaceAll methods
The Replacefirst and ReplaceAll methods are used to replace text that matches a regular expression. The difference is that Replacefirst replaces the first match, ReplaceAll replaces all matches.
The following example explains this feature:

Import Java.util.regex.matcher;import Java.util.regex.Pattern; Public classregexmatches{Private StaticString REGEX ="Dog";Private StaticString INPUT ="the dog says Meow."+"All dogs say meow.";Private StaticString REPLACE ="Cat"; Public Static void Main(string[] args) {Pattern p = pattern.compile (REGEX);//Get a Matcher objectMatcher m = P.matcher (INPUT);       INPUT = M.replaceall (REPLACE); System. out. println (INPUT); }}

The results of the above example compilation run as follows:

All cats say meow.

Appendreplacement and Appendtail methods
The Matcher class also provides appendreplacement and Appendtail methods for text substitution:
Take a look at the following example to explain this feature:

Import Java.util.regex.matcher;import Java.util.regex.Pattern; Public classregexmatches{Private StaticString REGEX ="A*b";Private StaticString INPUT ="Aabfooaabfooabfoob";Private StaticString REPLACE ="-"; Public Static void Main(string[] args) {Pattern p = pattern.compile (REGEX);//Get Matcher objectMatcher m = P.matcher (INPUT); StringBuffer SB =NewStringBuffer (); while(M.find ())      {m.appendreplacement (sb,replace);      } m.appendtail (SB); System. out. println (Sb.tostring ()); }}

The results of the above example compilation run as follows:

-foo-foo-foo-

Appendreplacement (StringBuffer SB, string replacement) replaces the current matching substring with the specified string, and adds the replaced substring and the string segment preceding it to the last matched substring to a StringBuffer object, and the Appendtail (StringBuffer sb) method adds the remaining string to a StringBuffer object after the last matching work.

methods of the Patternsyntaxexception class
Patternsyntaxexception is a non-mandatory exception class that indicates a syntax error in a regular expression pattern.
The Patternsyntaxexception class provides the following methods to help us see what errors have occurred.

Serial Number Method and Description
1 Public String getdescription ()
Gets the description of the error.
2 public int GetIndex ()
Gets the index of the error.
3 Public String Getpattern ()
Gets the regular expression pattern for the error.
4 Public String GetMessage ()
Returns a multiline string that contains a syntax error and a description of its index, an incorrect regular expression pattern, and a visual indication of the error index in the pattern.

Java Regular Expressions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.