Home > Software engineering >  Regex - Why non greedy mode not working in javascript?
Regex - Why non greedy mode not working in javascript?

Time:01-14

In javascript:

'a[b][c][d]'.match(/\[.*?\]$/)

*? means non-greedy mode and I suppose it should return [d] however [b][c][d] is returned. Why non-greedy not working?

CodePudding user response:

Your regex has a mistake

You are matching [.*?] non greedy which is OK, but then you have a $ which matches the end of the line, which forces the non-greedy to expand until the end of the line always

Just remove the "$" and it works just fine

'a[b][c][d]'.match(/\[.*?\]/)

enter image description here

CodePudding user response:

This also occurs in python

Python 3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.search(r'\[.*?\]$', 'a[b][c][d]')
<re.Match object; span=(1, 10), match='[b][c][d]'>

In matching, the first token \[ in pattern matched firstly then re finds for last two token \] and $, that's meaning

a[b][c][d] ($)
 ^ this matches \[
a[b][c][d] ($)
   ^^ these two char do not match '\]' '$'
a[b][c][d] ($)
         ^  ^ these two char match '\]' '$'

So you got the result, for this specific scene, you can use:

>>> re.search(r'\[[^[]*\]$', 'a[b][c][d]')
<re.Match object; span=(7, 10), match='[d]'>

in js:

'a[b][c][d]'.match(/\[[^[]*\]$/)

For this regex:

a[b][c][d] ($)
 ^ this matches \[
a[b][c][d] ($)
    ^ this do not match "[^[]", rolling back
a[b][c][d] ($)
    ^ this matches \[
a[b][c][d] ($)
       ^ this do not match "[^[]", rolling back
a[b][c][d] ($)
       ^ this matches \[
a[b][c][d] ($)
        ^ this match "[^[]"
a[b][c][d] ($)
         ^  ^ these match '\]' '$'
  •  Tags:  
  • Related