Regex with prefix and optional suffix

折月煮酒 提交于 2021-02-04 06:19:47

问题


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!


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/39723275/regex-with-prefix-and-optional-suffix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!