Matching text between delimiters: greedy or lazy regular expression?

后端 未结 3 562
时光说笑
时光说笑 2021-02-01 21:34

For the common problem of matching text between delimiters (e.g. < and >), there\'s two common patterns:

  • using the greedy *
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 21:53

    The first is more explicit, i. e. it definitely excludes the closing delimiter from being part of the matched text. This is not guaranteed in the second case (if the regular expression is extended to match more than just this tag).

    Example: If you try to match Hello! with <.*?>Hello!, the regex will match

    Hello!
    

    whereas <[^>]*>Hello! will match

    Hello!
    

提交回复
热议问题