PHP regular greedy way and lazy mode

Source: Internet
Author: User
PHP regular greedy mode and lazy mode
When a regular expression contains a qualifier that can accept duplicates, the usual behavior is to match as many characters as possible (in order for the entire expression to be matched). Consider this expression: A.*b, which will match the longest string starting with a and ending with B. If you use it to search for Aabab, it will match the entire string aabab. This is called a greedy match.

Sometimes we need more lazy matching, which is to match as few characters as possible. The qualifier given above can be converted to lazy matching mode, just add a question mark after it. So. * is meant to match any number of repetitions, but with minimal repetition in the premise that the entire match succeeds. Now look at the lazy version of the example:

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

Note that if I/I is used in pattern, it is case insensitive
/s represents. Also matches whitespace characters
/U indicates pattern reversal, that is, greedy match mode becomes lazy match mode, lazy match mode becomes greedy match pattern
  • 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.