![](/img/trans.png)
[英]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.