How to match a sentence between 2 words using regex?

Member

by lily , in category: Third Party Scripts , 5 days ago

How to match a sentence between 2 words using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 4 days ago

@lily 

To match a sentence between two specific words using regex, you can use a pattern like the following:

1
(?<=word1).*?(?=word2)


In this pattern:

  • (?<=word1) is a positive lookbehind assertion that matches the position right after "word1".
  • .*? matches any character (except for line terminators) zero or more times, as few times as possible.
  • (?=word2) is a positive lookahead assertion that matches the position right before "word2".


You can replace "word1" and "word2" with the specific words you want to match the sentence between. For example, if you want to match a sentence between "begin" and "end", the regex pattern would be:

1
(?<=begin).*?(?=end)


This pattern will match the shortest possible sentence between the two words "begin" and "end" in a string.