Greedy matching of regular expressions and lazy matching __my

Source: Internet
Author: User

Today used to regular expression of lazy match, because the beginning is not very understanding, so a problem tangled up a day, really understand it is not difficult.

Example: A string "ABCDAKDJD"

regex= "A.*?d"; Lazy Match

Regex2= "A.*d"; Greedy match


public static void Main (string[] args) {
		int count = 0;
		Scanner sc = new Scanner (system.in);
		String str = Sc.next ();
                String str = "ABCDAKDJD";
		String regex= "A.*?d";
			Pattern p = pattern.compile (regex);
			Matcher m = p.matcher (str);
			while (M.find ()) {
				count++;
				System.out.println (M.group ());
			}
			The number of System.out.println ("ABCDE" appears in the string "+str+" is "+count+");
	}

Results:

Abcd
Akd
ABCDE occurs 2 times in string ABCDAKDJD

Here is the lazy match, the match to meet the conditions of ABCD stopped this match, will not interfere with the continuation of the match.


When you change the regex= "A.*?d" to regex= "A.*d"

Results:

Abcdakdjd
ABCDE occurs 1 times in string ABCDAKDJD

Here is greedy match, as the name implies, very greedy, to maximize the occupancy of the string.

The above two, one is try to match the shortest string, one is to match the longest string.

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.