olexd
olexd

Reputation: 1420

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!

Upvotes: 4

Views: 15083

Answers (2)

Thomas
Thomas

Reputation: 88707

Try prefix(.*?)(?:/?(?:suffix|$)) if there are characters allowed before prefix of after suffix.

This requires the match to be as short as possible (reluctant quantifier) and be preceeded by one of 3 things: a single slash right before the end of the input, /suffix or the end of the input. That would match /s/o/m/e/t/h/i/n/g in the test cases you provided but would match more for input like prefix/s/o/m/e/t/h/i/n/g/suff (which is ok IMO since you don't know whether /suff is meant to be part of the match or a typo in the suffix).

Upvotes: 1

SamWhan
SamWhan

Reputation: 8332

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.

Upvotes: 7

Related Questions