java-Regular Expression method

Source: Internet
Author: User

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.
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.

Instance:

1 ImportJava.util.regex.Pattern;2 ImportJava.util.regex.Matcher;3 4  Public classregexmatches{5      Public Static voidMain (String args[]) {6         //find in string by specified pattern7String line = "This order is placed for qt3000! OK? ";8 9String pattern = "(. *) (\\d+) (. *)";Ten  OnePattern R = pattern.compile (pattern);//Create a Pattern object AMatcher m = r.matcher (line);//now create the Matcher object -  -      if(M.find ()) { theSystem.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 ("Not Found"); +      } A     } at}
Found value:this Order is placed for qt3000! Ok? Found value:this Order is placed for Qt300found value:0


Methods of the Mather class
Index methods-start and End methods

1 ImportJava.util.regex.Pattern;2 ImportJava.util.regex.Matcher;3  Public classregexmatches4 {5     Private Static FinalString REGEX = "\\bcat\\b";6     Private Static FinalString INPUT = "Cat cat cat Cattie Cat";7 8      Public Static voidMain (String args[]) {9Pattern p =Pattern.compile (REGEX);TenMatcher m =P.matcher (INPUT); One         intCount = 0; A          while(m.find) { -count++; -System.out.println ("Match number" +count); theSystem.out.println ("Start ():" +M.start ()); -System.out.println ("End ():" +m.end ()); -         } -}


Compile results

Match number 1start (): 0end (): 3Match number 2start (): 4end (): 7Match number 3start (): 8end (): 11Match number 4start (): 19 End (): 22


Index methods-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.

1 ImportJava.util.regex.Pattern;2 ImportJava.util.regex.Matcher;3 4  Public classregexmatches{5     Private Static FinalString REGEX = "foo";6     Private Static FinalString INPUT = "Fooooooooooooo";7     Private Staticpattern pattern;8     Private StaticMatcher Matcher;9 Ten      Public Static voidMain (String args[]) One     { APattern =Pattern.compile (REGEX); -Matcher =Pattern.matcher (INPUT); -  theSystem.out.println ("Current REGEX is:" +REGEX); -System.out.println ("Current INPUT is:" +INPUT); -  -System.out.println ("Lockingat ():" +Matcher.lockingat ()); +System.out.println ("Matches ():" +matcher.matches ()); -     } +}

Compile results

Current REGEX is:foocurrent INPUT Is:fooooooooooooooooolookingat (): Truematches (): false

Index methods-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

1 ImportJava.util.regex.Pattern;2 ImportJava.util.regex.Matcher;3 4  Public classregexmatches{5     Private StaticString REGEX = "Dog";6     Private StaticString INPUT = "the dog says Meow." + "All dogs say meow.";7     Private StaticString REPLACE = "Cat";8      Public Static voidMain (string[] args) {9Pattern p =Pattern.compile (REGEX);Ten        //gets a Matcher object OneMatcher m =P.matcher (INPUT); AINPUT =M.replaceall (REPLACE); - System.out.println (INPUT); -}
}

Compile results
The cat says Meow. All cats say meow.

Index methods-appendreplacement and Appendtail methods
The Matcher class also provides appendreplacement and Appendtail methods for text substitution

1 ImportJava.util.regex.Matcher;2 ImportJava.util.regex.Pattern;3 4  Public classregexmatches{5     Private StaticString REGEX = "A*b";6     Private StaticString INPUT = "Aabfooaabfoob";7     Private StaticString REPLACE = "-";8      Public Static voidMain (String args[]) {9Pattern p =Pattern.compile (REGEX);TenMatcher m =P.matcher (INPUT); OneStringBuffer SB =NewStringBuffer (); A  -          while(M.find ()) { - m.appendreplacement (sb,replace); the         } - M.appendtail (SB); - System.out.println (sb.tostring ();) -}

Compile results
-foo-foo-foo-



Methods for indexing methods-patternsyntaxexception classes
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.
The following methods:
Public String getdescription ()
Gets the description of the error.
public int GetIndex ()
Gets the index of the error.
Public String Getpattern ()
Gets the regular expression pattern for the error.
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 Expression method

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.