Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with prefix and optional suffix

This is maybe the 100+1 question regarding regex optional suffixes on SO, but I didn't find any, that could help me :(

I need to extract a part of string from the common pattern:

prefix/s/o/m/e/t/h/i/n/g/suffix

using a regular expression. The prefix is constant and the suffix may not appear at all, so prefix/(.+)/suffix doesn't meet my requirements. Pattern prefix/(.+)(?:/suffix)? returns s/o/m/e/t/h/i/n/g/suffix. The part (?:/suffix)? must be somehow more greedy.

I want to get s/o/m/e/t/h/i/n/g from these input strings:

prefix/s/o/m/e/t/h/i/n/g/suffix
prefix/s/o/m/e/t/h/i/n/g/
prefix/s/o/m/e/t/h/i/n/g

Thanks in advance!

like image 835
olexd Avatar asked Oct 22 '25 04:10

olexd


1 Answers

Try

prefix\/(.+?)\/?(?:suffix|$)

The regex need to know when the match is done, so match either suffix or end of line ($), and make the capture non greedy.

See it here at regex101.

like image 139
SamWhan Avatar answered Oct 24 '25 18:10

SamWhan