[英]Use Python to match a letter in a string only when followed by a space, period, or nothing, without regex?
[英]python regex match number followed by string or nothing
如何匹配紧跟/ tcp或/ udp或什么都没有的数字?
下面说明了3种情况:输入->结果
我用过re.compile(r'(\\d+)(?:\\/[tcpud]{3})*')
但在情况3中也匹配了。
编辑:猜猜这确实是一个后续问题:如何匹配/ tcp或/ udp后面的数字,或者tcp /或/ udp后面的数字,或者仅是它自己? 所以
1. something else 123/tcp_haha --> 123
2. 123 --> 123
3. 123abc/tcp --> no match
4. udp/123 something else --> 123
5. tcp/123/tcp --> 123
字符类将匹配其包含的字符的任何组合。 您需要使用逻辑或。
r'^\d+(?:/tcp|/udp)?$'
?:
是非捕获组符号, ?
将使您的非捕获组成为可选的(对于非后缀情况)。
如果要在/tcp
之后跟随某项来捕获字符串,则可以使用以下正则表达式:
r'^\d+(?:/tcp.*|/udp)?$'
对于您的原始问题呢?
^\d+(?=/tcp|/udp|$)
编辑后使用此正则表达式 :
\d+(?=\/tcp|\/udp)
\\d+
匹配一个或多个数字 (?=...)
是先行的,如果下一个字符是...,匹配将停止。 \\/tcp|\\/udp
匹配一个斜杠,后跟tcp
或udp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.