PHP Regular Expressions (. *) and (. *?) Difference

Source: Internet
Author: User

When a regular expression contains a repeating quantifier (such as: *,?, +), the usual behavior is to match as many characters as possible, such as: a (. *) b to match the Aabab string, which matches the entire string, which is called a greedy match.


$str = ' Aabab ';
Preg_match ("/A (. *) b", $str, $matches);
Print_r ($matches);

Array ([0]=>aabab [1]=>[aba])

Sometimes we need a lazy match, which is to match as few characters as possible, and then add a question mark behind the classifier, such as (. *?) Use minimal repetition if the entire match is successful.

$str = ' Aabab ';
Preg_match ("A"/A (. *?) b/", $STR, $matches);
Print_r ($matches);

Array ([0]=>aab [1]=>[a])

Analytical

? involving greedy patterns

When a regular expression contains a qualifier that accepts duplicates, the usual behavior is to match as many characters as possible (subject to the entire expression being matched). Take this expression as an example: A.*b, it will match the longest string that begins with a and ends with a B. If you use it to search for Aabab, it will match the entire string aabab. This is called greedy match.

Sometimes we need a lazy match, which is to match as few characters as possible. The qualifier given above can be converted to lazy match mode, just add a question mark after it. this. * means matching any number of repetitions, but using the least repetition if the whole match succeeds. Now look at the lazy version of the example:

A.*?b matches the shortest string, starting with a and ending with B. If applied to Aabab, it will match AaB (first to third characters) and AB (fourth to fifth characters)

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.