How to match a sentence between 2 words using regex?

Member

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

How to match a sentence between 2 words using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 5 months 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.

Related Threads:

How to match complete words for acronym using regex?
How to match all words after a specific expressions with regex?
How to match & symbols which inside brackets using regex?
How to set max limit for each word in the sentence using regex in java?
How to find a sentence and a 13 digit code in a paragraph in regex?
How to replace spaces between words using regex?