How to match part of the string contains certain word

Question:

I want to be able to match the following texts

top of radio 54 / bottom 27
radio top 54 / bottom 27

The word top can be before or after radio only for the first half of the text (before /). top that appears after / should not be matched.

I tried to use the following pattern that encloses the lookahead for the first half with parentheses.

((?=top).*radiosd{2}s)/D*bottomsd{2}

But it doesn’t work like I expected. Only matches first string, but not second.

Asked By: ddd

||

Answers:

You may use this regex with a lookahead:

^(?=[^/]*btops)[^/]*radio[^/]+d{2}s+/D*bottoms+d{2}$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (?=[^/]*btops): Lookahead to assert presence of word top being present before matching a /. This is to ensure we match word top before / only
  • [^/]*: Match 0 more of any char that is not a /
  • radio: Match radio
  • [^/]+: Match 1+ of any char that is not a /
  • d{2}: Match 2 digits
  • s+: Match 1+ whitespaces
  • /: Match a /
  • D*: Match 0 or more non-digits
  • bottom: Match bottom
  • s+: Match 1+ whitespace
  • d{2}: Match 2 digits
  • $: End
Answered By: anubhava
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.