[Migration text] Java RegEx. matcher example (group () method usage)

Source: Internet
Author: User

With regard to pattern, various matcher functions have javadoc.

However, there is still one point to emphasize. The first is this group. In fact, there are groupcount + 1 groups.

Group (0) corresponds to the matching part of the entire regular expression, group (1 )~ Group (groupcount) is the matching part in parentheses.

And the object of this group is the string that the regular expression matches after one find.

For example, if a string, (S1) XXX (S2) has the S1 and S2 parts that meet the requirements, after a single find, all groups are inside the S1

After the second find, all groups are in S2

 

1 import java. util. RegEx. matcher;
2 Import java. util. RegEx. pattern;
3
4 public class regextest {
5
6 public static void printmatched (string RegEx, string source ){
7 pattern P = pattern. Compile (RegEx );
8 matcher M = P. matcher (source );
9 While (M. Find ()){
10 For (INT I = 0; I <= M. groupcount (); I ++ ){
11 system. Out. println (M. Group (I ));
12}
13}
14}
15
16 public static void main (string [] Arg ){
17 regextest. printmatched ("<(\ W +)>. * </(\ 1)> ",
18 "<Table> <TD> sdjfjfiweif </TD> </table> <Cd> sdfsdf </Cd> ");
19
20}
21}
22

 

[Supplement] in Java, the string methods replace and replaceall are bothAllMatch. Only replaceall supports regular expressions.

Many people use replaceall as replace. If something goes wrong, they still don't know what's going on.

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.