"Java Regular expression"

Source: Internet
Author: User
Tags ming

First, the string class.

Java.lang.Object

|--java.lang.string

Common methods:

 String

replaceAll(String regex, String replacement)
Replaces this string with the given replacement for all substrings that match the given regular expression.

 String[]

split(String regex)
Splits This string according to the match of the given regular expression.

 boolean

matches(String regex)
tells whether this string matches a given regular expression.

Second, the pattern class.

Java.lang.Objet

|--java.util.regex.pattern

A regular expression that is specified as a string must first be compiled into an instance of this class. The resulting pattern can then be used to create an Matcher object that, according to the regular expression, can match any sequence of characters . In simple terms, regular expressions are encapsulated as pattern objects before they can be useful. It works with the Matcher object.

Therefore, the typical invocation order is

Pattern p = pattern. compile ("A*b"); Matcher m = p. matcher ("Aaaaab"); Boolean b = M. matches ();

This class is a convenient way to define a method when you use only one regular expression matches . This method compiles an expression and matches the input sequence in a single call. Statement

Boolean B = pattern.matches ("A*b", "Aaaaab");

Construction Method: None

To obtain the method of the Pattern object:

static Pattern

compile(String regex)
compiles the given regular expression into the pattern.

Common methods:

 Matcher

matcher(CharSequence input)
Creates a match for the given input with this pattern.

static boolean

matches(String regex, CharSequence input)
compiles the given regular expression and attempts to match the given input with it. This method is a static method of the pattern class, and it is not necessary to obtain an instance of the pattern class.

 String

pattern()
returns the regular expression in which this pattern has been compiled.

Three. Matcher class.

Java.lang.Object

|-java.util.regex.matcher

Construction method: No.

Gets the method of the class object:

Use the Matcher method of the pattern class. This is the only way to get instances of this class

Common methods:

 int

end()
Returns the offset after the last matching character.

boolean

find()
attempts to find the next subsequence of the input sequence that matches the pattern.

 String

group()
Returns the input subsequence that was matched by the previous match operation.

boolean

matches()
try to match the entire region to the pattern.

 String

replaceAll(String replacement)
the replacement pattern matches each subsequence of the input sequence with the given replacement string.

 int

start()
Returns the initial index of the previous match.

Four, the regular expression function classification.

1. Match.

The matches method of the string class is actually used.

 boolean

matches(String regex)
tells whether this string matches a given regular expression.

Requirements: Verify that the phone number format is correct.

Analysis: Mobile phone number should be 11 digits, all should be a number, the first number is 1, assuming the second digit should be 3 or 5 or 8

The corresponding pattern is: 1[358][0-9]{9} or 1[358]\d{9}

Code:

1 Private Static void Checkphonenumber () {2         String phone= "15791916245"; 3         String regex= "1[358]\\d{9}"; 4         System.out.println (phone.matches (regex)); 5     }
View Code

Run result is true

2. Cutting.

The split method of the string class is actually used.

 String[]

split(String regex)
Splits This string according to the match of the given regular expression.

Take word exercises.

(1) The delimiter is a number of contiguous spaces.

The mode used is: "+"

Code:

1 Private Static void Getdanci () {2         String str= "Xiao  Qiang      zhaosan       Lisi"; 3         String regex= "+"; 4         String arr[]=str.split (regex); 5          for (String S:arr) 6             System.out.println (s); 7     }
View Code

(2) The delimiter is a number of consecutive non-whitespace symbols, and the delimiter type is not unique.

The mode used is: "(.) \\1+ "." Here stands for any character, not just. If you want to use. Cut string, you need to escape: \ \.; Where parentheses are used to represent groupings, and the latter \\1 represent the first group, if you want to use "first group number 1" instead of the mere number 1, you need to use \ \ To escape.

Group: ((A) (B (C))), who is the first group, and who is the second group? start with the left parenthesis and start counting.

Code:

1 Private Static void GetDanCi2 () {2         String str= "[Email protected]@@@ zzfcthotfixz # # # # #王五 $]; 3         String regex= "(.) \\1+ "; 4         String arr[]=str.split (regex); 5          for (String S:arr) 6             System.out.println (s); 7     }
View Code

3. Replace

The ReplaceAll method of the string class is actually used.

 String

replaceAll(String regex, String replacement)
replaces this string with the given replacement for all substrings that match the given regular expression.

(1). Change the string "[email protected]@@@@ zzfcthotfixz &&&&&&&wangwu******zhaoliu-------" to all the words in #.

The mode used is: "(.) \\1+ "

Code:

1 Private Static void Replacedemo () {2         String str= "[Email protected]@@@@ zzfcthotfixz &&&&&&&wangwu******zhaoliu-------"; 3         String regex= "(.) \\1+ "; 4         Str=str.replaceall (Regex, "#"); 5         System.out.println (str); 6     }
View Code

Running Result: zhangsan#lisi#wangwu#zhaoliu#

(2). String "[email protected]@@@@ zzfcthotfixz &&&&&&&wangwu******zhaoliu-------" All of the overlapping words in the original overlapping words in a single symbol.

Mode used: Same as 1, but when calling the Repalaceall method, the second parameter uses $ $, and the $ symbol allows the group in the first argument to be used in the latter argument, followed by a number representing the group number.

Code:

1     Private Static void ReplaceDemo2 () {2         String str= "[Email protected]@@@@ zzfcthotfixz &&&&&&&wangwu******zhaoliu-------"; 3         String regex= "(.) \\1+ "; 4         Str=str.replaceall (Regex, "$"); 5         System.out.println (str); 6     }
View Code

Operation Result: [Email protected]&wangwu*zhaoliu-

(3). Block out some numbers in the number and replace the original number with an * number.

For example: 18369905102 becomes 183*****102

Mode used: "(\\d{3}) (\\d{4}) (\\d{4})"

Code:

1 Private Static void ReplaceDemo3 () {2         String str= "13991716243"; 3         String regex= "(\\d{3}) (\\d{4}) (\\d{4})"; 4         Str=str.replaceall (Regex, "$1****$3"); 5         System.out.println (str); 6     }
View Code

Running Result: 139****6243

4. Access.

The acquisition of regular expressions can only be implemented using the pattern class and the Matcher class, and none of the rest can implement this function.

The main method used is the Matcher class.

boolean

find()
Attempts to find the next subsequence of the input sequence that matches the pattern.

 String

group()
Returns the input subsequence that was matched by the previous match operation.

Two methods.

Practice:

Get "da Jia hao,ming tian Bu fang jia!" A three-letter word in the

The mode used is: "\\b[a-za-z]{3}\\b", \b is the word boundary

Code:

1 Private Static voidGetDemo1 () {2list<string>list=NewArraylist<string>();3String str= "da Jia hao,ming tian Bu fang jia!";4String regex= "\\b[a-za-z]{3}\\b";5Pattern p=pattern.compile (regex);6Matcher m=P.matcher (str);7          while(M.find ())8         {9 List.add (M.group ());Ten         } One          for(String s:list) A System.out.println (s); -}
View Code

Operation Result:

Jia
Hao
Jia

It should be noted that if the Start method and the End method are used, the output is:

3:6
7:10
29:32
Jia
Hao
Jia

Start () is the start index number, starting with 0, end () is the ending index number, and the header contains no tail.

"Java Regular expression"

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.