Four usages of regular expression question mark--Regular expression

Source: Internet
Author: User

Original symbol

Because there is a special meaning in the regular expression, so if you want to match it, you need to escape, \?

There are no quantifiers

A question mark can indicate that you repeat the previous content 0 or one time, that is either not present or occurs once.

Non-greedy match

Greedy match

Matches the string as long as possible when matching matches, by default, with greedy matching

String pattern1 = @ "A.*c";  Greedy match 
regex regex = new Regex (PATTERN1);
Regex. Match ("Abcabc"); Return "ABCABC"

Non-greedy match

Matches as short as possible when matching matches, using? to indicate non-greedy matches

String pattern1 = @ "A.*?c";  Non-greedy match 
regex regex = new Regex (PATTERN1);
Regex. Match ("Abcabc"); Return "ABC"

Several commonly used non-greedy matching pattern

*? Repeat any time, but try to repeat as little as possible
+? Repeat 1 or more times, but repeat as little as possible
?? Repeat 0 or 1 times, but repeat as little as possible
{n,m}? Repeat N to M times, but repeat as little as possible
{N,}? Repeat more than n times, but repeat as little as possible

Do not capture mode

How do I turn off the ability to capture parentheses? Instead of using it to group, the method is to add the following in the left parenthesis:?, where the first parenthesis is used for grouping only, not capturing the variable, so the contents can only be steak or burger, and can never be bronto.

while (<>) {
  if (/?: Bronto) (Steak|burger)/) {
    print "Fred wants a $1\n";
  }
}

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.