Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: match between last occurrence of a character and first occurrence of another character

Tags:

regex

I have the following string:

COUNTRY/CITY/street_number_floor_tel

I'd like to extract what is after the last occurrence of '/' and first occurrence of '_'. So the result is:

street

So far I've managed to come up with this regex:

[^/]+(?=_)

which results in the following:

street_number_floor

So I basically don't know how to stop after finding the first occurrence of '_'.

Many thanks for any hints in advance!

like image 340
0x4ndy Avatar asked Oct 27 '25 21:10

0x4ndy


1 Answers

You may use

(?<=/)[^/_]+(?=_[^/]*$)

See the regex demo

Details

  • (?<=/) - a positive lookbehind requiring a / immediately before the match
  • [^/_]+ - 1+ chars other than / and _
  • (?=_[^/]*$) - a positive lookahead that requires _, then 0+ chars other than / till the end of string immediately to the right of the current location.
like image 200
Wiktor Stribiżew Avatar answered Oct 29 '25 18:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!