Java advanced regular expression group capture reference

Source: Internet
Author: User

To repeat a single character, it is very simple. Simply add a qualifier after the character. For example, a + indicates matching one or more of the,? Matches 0 or 1. These delimiters are as follows:X?X, Neither once nor onceX*X, Zero or multiple timesX+X, Once or multiple timesX{N}X, Exactly
NTimesX{N,}X, At leastNTimesX{N,M}

X, At leastNTimes, but no moreMTimes

But what if we want to repeat multiple characters? Now we need to use grouping. We can use parentheses "()" to specify the child expression to be repeated, and then repeat the child expression, for example: (abc )? Represents 0 or 1 abc. The expression in parentheses represents a group.

A group can be divided into capture groups and non-capture groups.

Capture Group

The capture group can be numbered from left to right by calculating its parentheses. For example(A) (B (C )))There are four such groups:

1(A) (B (C )))2\3(B (C ))4(C)

Group zero always represents the entire expression

The reason for naming the capture group is that each sub-sequence of the input sequence that matches these groups is saved in the match. The captured sub-sequence can be used in the expression through Back reference later, or it can be retrieved from the matcher after the matching operation is completed.

Back Reference means that in the following expressions, we can use the group number to reference the text sequence captured by the previous expression (text is not a regular expression ).

For example (["']). * \ 1 uses a group, and \ 1 is a reference to the group. It matches all strings contained in two or two single quotes, for example, "abc" or "'" or' "', but note that it does not match" A' or 'A. As described above, Back Reference only references text rather than expressions.

Non-capturing Group

To(?)The group at the beginning is pureNon-capturingGroup, which does not capture text or count the combined counts. That is to say, if we use? The Group does not capture text or contain group numbers. Therefore, there is no back reference.

In Java, the following types of non-capturing groups are supported:

(? =X)X, Through the zero-width positive lookahead(?!X)X, Using a zero-width negative lookahead(? <=X)X, Through the zero-width positive lookbehind(? <!X)X, Using a zero-width negative lookbehind

These four non-capturing groups are used to match expression X, but do not contain the expression text.

(? = X) assertion with zero width. The child expression x continues matching only when it matches the right side of the position. For example, \ W + (? = \ D) matches the word followed by a number instead of the number. This construction will not be traced back. (?! X) assertion with Zero Width and negative first. The matching continues only when the child expression X does not match the right side of the position. For example, \ W + (?! \ D) It does not match the word with the digit, but does not match the digit. (? <= X) Assertion after positive development with zero width. The child expression x continues matching only when it matches the left side of this position. For example ,(? <= 19) 99 matches the 99 instance following 19. This construction will not be traced back. (? <! X) Assertion after negative width. Only when the subexpression
X is not matched on the left side of this position. For example ,(? <! 19) 99 matches with 99 instances not following 19

Example:

The above is a theoretical introduction. Here we will use some examples to illustrate the problem:

1. Test Matching (? <! 4) 56 (? = 9) The meaning here is that the first part of the matched text 56 cannot be 4, and the last part must be 9. Therefore, it can match the following text 5569, not 4569.

2. Extract the string da12bka3434bdca4343bdca234bm to extract numbers between characters a and B. However, the character before a cannot be C, and the character after B must be D.

For example, only the number 3434 meets the requirements. So how can we extract it?

First, we write the expression for extracting this string :(? <! C) a (\ d +) bd there is only one capture group (\ d +)

The JAVA code snippets are as follows:

  1. Pattern p = Pattern. compile ("(? <! C) (");
  2. Matcher m = p. matcher ("da12bca3434bdca4343bdca234bm ");
  3. While (m. find ()){
  4. System. out. println (m. group (1); // you only need to capture the number of group 1. Result 3434
  5. System. out. println (m. group (0); // The 0 group is the entire expression. Here, it is not extracted (? <! C. Result: a3434bd
  6. }

As you can see, non-capturing groups do not return results because they do not capture text.

Finally, two solutions are used:

Solution 1: A stupid method without a non-capturing group:

Pattern p = Pattern. compile ("<(. *)>. * </\ 1> ");......

Matcher m = p. matcher (line );
HashSet setstr = new HashSet ();
While (m. find ()){
If (! Setstr. contains (m. group (1 ))&&! Setstr. isEmpty ()){
// The line here is the content that meets the requirements

Solution 2: Use a non-capturing Group

Pattern p = Pattern. compile ("<(. *)>. * </\ 1>. * <(?! \ 1 )");
A regular expression can solve the problem.

It proves the importance of a regular expression again.

Http://www.inmvc.com (IN-MVC open source architecture, java ee architect Practice)

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.