Hows does the Regular Expression: /.+?/ work?

regex

Solution

Besides what Hans Kesting already said, a lazy multiplier will do the exact oposite of the normal greedy multipliers: The possible match is kept as small as possible and the rest of the regular expression is tested.

So if you’re having the string `aaba` and test the regular expression `a.*b` on it, the internal processing steps would be as follows:

- `a` in `a``.*b` matches `a``aba`

- `.*` in `a``.*``b` matches `a``a``ba`, and since `.*` is greedy

- `.*` then matches `a``ab``a`

- `.*` then matches `a``aba`

- `b` in `a.*``b` fails as there is no letter left

- backtracking goes one step back and `.*` will now only match `bb` in `a``ab``a`

- `b` in `a.*``b` still fails on `aab``a`

- backtracking goes one step back and `.*` now matches only `b` in `a``a``ba`

- `b` in `a.*``b` now matches `b` in `aa``b``a` and we’re done.

So the full match is `aab``a`.

If we do the same with a lazy multiplier (`a.*?b`), the processing will do the oposite, try to match the least possible characters as possible:

- `a` in `a``.*?b` matches `a``aba`

- `.*` in `a``.*``?b` matches nothing (`*` = zero or more repetitions), and since `.*` is declared as lazy (`.*?`), the rest of the regular expression is tested

- `b` in `a.*?``b` fails on `a``a``ba`

- backtracking will try to increase the match of `.*`

- `.*` matches now `a``a``ba`

- `b` in `a.*?``b` matches `aa``b``a` and we’re done.

So the full match if `aab``a`.

Problem

How would the '.+?' regular expression work? Is the .+ part matching anything written, and the ? part saying it can either be there or not? So, for example, this regular expression would match: 'cat' '' (ie, nothing written, just the empty string)

Original source

Related problems