Is the lazy version of the 'optional' quantifier ('??') ever useful in a regular expression?

前端 未结 2 614
暖寄归人
暖寄归人 2020-12-06 12:35

I cannot think of a situation where I\'d want to use ?? in a regular expression, but maybe I\'m not thinking hard enough.

相关标签:
2条回答
  • 2020-12-06 12:46

    I would use it as an optimization if the optional part is usually absent.

    Foo(PartUsuallyPresent)?Bar
    
    Foo(PartUsuallyAbsent)??Bar
    

    But I definitly lack a real-world example, too.

    0 讨论(0)
  • 2020-12-06 13:09

    Maybe a delimiter-separated list, and you don't want to match any terminating delimiter.

    ^((?:[^,]+,??)+),?$
    

    That would capture "a,b,c" from "a,b,c,", where as the non-lazy variant would include the comma in the capture-group.

    0 讨论(0)
提交回复
热议问题