Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...