Java regular expressions match and find match locations

Source: Internet
Author: User

Java regular expressions match and find match locations

For example, if the matching position of the Methods matching the Regular Expression in java is unclear, a few examples are provided. As follows:

 

  String ss="ooaaoo";        Pattern pt=Pattern.compile("(o+)");        Matcher mt=pt.matcher(ss);       // mt.lookingAt();       // mt.matches();        while(mt.find()){        System.out.println(mt.group(1)+"|||"+mt.start());        }

This result will obviously match twice, one at 0 and one at 4.

 

See the following code.

  String ss="ooaaoo";        Pattern pt=Pattern.compile("(o+)");        Matcher mt=pt.matcher(ss);           mt.lookingAt();       // mt.matches();        while(mt.find()){        System.out.println(mt.group(1)+"|||"+mt.start());        }
After we remove the annotation of one of the matches or lookingat methods, only one matching occurs, that is, at 4 locations.

 

Let's look at the following code:

 

String ss="aaooaaoo";        Pattern pt=Pattern.compile("(o+)");        Matcher mt=pt.matcher(ss);          mt.lookingAt();       // mt.matches();        while(mt.find()){        System.out.println(mt.group(1)+"|||"+mt.start());        }
Our input string ss has changed. The result of this program will be a secondary match, one at 2 and one at 4.

 

Therefore, the following conclusions can be drawn:

1. When the input string starting with ss does not match the regular expression, matches and lookingat do not affect the next matching position.

2. If a regular expression is matched at the beginning of the input string, after you call matches or lookingat, the next matching position will be removed after the string that matches the start.
 

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.