RegEx: Smallest possible match or nongreedy match

后端 未结 3 637
栀梦
栀梦 2020-11-27 02:56

How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?

3条回答
  •  [愿得一人]
    2020-11-27 03:20

    For a regular expression like .* or .+, append a question mark (.*? or .+?) to match as few characters as possible. To optionally match a section (?:blah)? but without matching unless absolutely necessary, use something like (?:blah){0,1}?. For a repeating match (either using {n,} or {n,m} syntax) append a question mark to try to match as few as possible (e.g. {3,}? or {5,7}?).

    The documentation on regular expression quantifiers may also be helpful.

提交回复
热议问题