Описание тега non-greedy
A regex is used to check if a string matches a certain pattern. Most regexes offer additional functionality to capture interesting parts of the string.
Example:
Say we have the following regular expression:
^(.*)([ab]+)$
The regex specifies a pattern: strings can start with any sequence of arbitrary characters, but should end with at least one a
or b
.
Wildcard operations are by default greedy. This means that the first group will aim to capture as much as possible (without losing the match) and only give up the remainder of the string if this is the only way to match the string with the pattern.
For instance the string foobaraabbabbababab
will be captured as (foobaraabbabbababa)(b)
. In case we more interested in the ([ab]+)
, group, we can apply a non-greedy operator on the first group such that the remainder of the string is passed to the second group as soon as possible.
In case we use the following pattern:
^(.*?)([ab]+)$
The example will be matched as (foobar)(aabbabbababab)
Related tags: