Regex Match all characters between two strings

后端 未结 14 1022
星月不相逢
星月不相逢 2020-11-21 07:42

Example: \"This is just\\na simple sentence\".

I want to match every character between \"This is\" and \"sentence\". Line breaks should be ignored. I can\'t figure o

14条回答
  •  被撕碎了的回忆
    2020-11-21 08:12

    Lazy Quantifier Needed

    Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because

    (?<=This is)(.*)(?=sentence)
    

    will match my first sentence. This is my second in This is my first sentence. This is my second sentence.

    See demo.

    You need a lazy quantifier between the two lookarounds. Adding a ? makes the star lazy.

    This matches what you want:

    (?<=This is).*?(?=sentence)
    

    See demo. I removed the capture group, which was not needed.

    DOTALL Mode to Match Across Line Breaks

    Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s), turning the expression into:

    (?s)(?<=This is).*?(?=sentence)
    

    Reference

    • The Many Degrees of Regex Greed
    • Repetition with Star and Plus

提交回复
热议问题