Regex to first occurrence only?

前端 未结 4 1108
暖寄归人
暖寄归人 2020-11-29 11:18

Let\'s say I have the following string:

this is a test for the sake of testing. this is only a test. The end.

and I want to se

4条回答
  •  眼角桃花
    2020-11-29 12:06

    Andy E and Ipsquiggle have the right idea, but I want to point out that you might want to add a word boundary assertion, meaning you don't want to deal with words that have "this" or "test" in them-- only the words by themselves. In Perl and similar that's done with the "\b" marker.

    As it is, this(.*?)test would match "thistles are the greatest", which you probably don't want.

    The pattern you want is something like this: \bthis\b(.*?)\btest\b

提交回复
热议问题