带有前缀和可选后缀的正则表达式 [英] Regex with prefix and optional suffix

查看:135
本文介绍了带有前缀和可选后缀的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是关于SO上正则表达式可选后缀的100 + 1问题,但我没有找到任何可以帮助我的地方:(

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

使用正则表达式.前缀是常量,后缀可能根本不出现,因此 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.

我想从这些输入字符串中获取 s/o/m/e/t/h/i/n/g :

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

提前谢谢!

推荐答案

尝试

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.

在regex101上看到它.

这篇关于带有前缀和可选后缀的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆