簡體   English   中英

如何使正則表達式匹配全部或不匹配

[英]How do make regex match all or nothing

我希望 RegEx 匹配組成有效 IP、冒號和端口的字符串。 如果該字符串包含有效的 IP 和無效的端口號,反之亦然,我希望它完全不匹配。 我正在 C# 應用程序中實現它。

為此,我正在嘗試整合如何查找或驗證 IP 地址中的以下內容

(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

使用正則表達式中的以下端口號

((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))

這些中的每一個都獨立工作以匹配 IP 地址和端口號就好了。

我把它們結合起來

(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\:((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))

結果是,例如:

256.250.139.193:1234  // bad IP, good port. The RegEx matches "56.250.139.193:1234". Fail. I want it to match nothing
1.1.1.1:65535         // good IP, good port #. The RegEx matches "1.1.1.1:65535". Pass. This is what I want it to do
1.1.1.1:65536         // good IP, bad port, matches "1.1.1.1:". Fail. I want it to match nothing

我無法弄清楚如何將它們組合起來以匹配全部或不匹配。 我嘗試使用重復和分組,它要么沒有改變匹配的內容,要么完全破壞了正則表達式

在模式周圍放置單詞邊界。

此外,您的端口號模式有誤。 [0-5]{0,5}應該是[0-5]{1,5} ,否則匹配空端口號。

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{1,5})|([0-9]{1,4}))\b

演示

一種可靠且可讀的方式,使用特定的 Perl 解析器Regexp::Common

perl -MRegexp::Common -lne '
    my ($ip, $port) = /^($RE{net}{IPv4}):(\d+)$/;
    print "$ip:$port" if defined $ip and defined $port and $port  < 65536
' file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM