Java finds all strings that match a regular substring in a string __java

Source: Internet
Author: User

The code is as follows:

String line = "October 11, 2016 Where do we go to play recently we recently, the following year, the same years, October, 2019, March 4" pattern
Datepattern = Pattern.compile ("\\d{4} year \\d {1,2} month \\d{1,2} Day |\\d{4} year \\d{1,2} |\\d{1,2} month \\d{1,2} Day |\\d{4} |\\d{1,2} month | The same year | The following week | recently | recently ");
Matcher datematcher = Datepattern.matcher (line);
int datecount = 0;
while (Datematcher.find ()) {
    System.out.println (Datematcher.group ());
    ++datecount;
}
As the code above is lookup, all the matches in the string are: month, month, year, months, months, years, year, day, recent, recently, substring

This involves greedy matching or not greedy match, as if with the regular order, as above, I will long match in front, namely first month, month, day, year, month and so on. I put the regular in this order, so I can achieve greedy matching.


Furthermore

If you have the following string

String line = "[[444444444444],[5555555555555]]";

I'm going to take the string out of each [] individually, and I can use the following regular

Pattern Categorypattern = Pattern.compile ("\\[\". *?\ "\]"); When you add a question mark, it's a greedy match.
Note: If none of the above. The number is greedy regular, this will only match to the outermost, that will only match to one, but add a question mark to become not greedy, you can achieve the right match

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.