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.
Answers:
You may use this regex with a lookahead:
^(?=[^/]*btops)[^/]*radio[^/]+d{2}s+/D*bottoms+d{2}$
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
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.
You may use this regex with a lookahead:
^(?=[^/]*btops)[^/]*radio[^/]+d{2}s+/D*bottoms+d{2}$
RegEx Breakup:
^
: Start(?=[^/]*btops)
: Lookahead to assert presence of wordtop
being present before matching a/
. This is to ensure we match wordtop
before/
only[^/]*
: Match 0 more of any char that is not a/
radio
: Matchradio
[^/]+
: Match 1+ of any char that is not a/
d{2}
: Match 2 digitss+
: Match 1+ whitespaces/
: Match a/
D*
: Match 0 or more non-digitsbottom
: Matchbottom
s+
: Match 1+ whitespaced{2}
: Match 2 digits$
: End