簡體   English   中英

Perl中的正則表達式為排除模式,但包含模式

[英]regular expression in Perl to excluded patterns but include pattern

我想有一個正則表達式模式來匹配一行:
1.此行必須包含單詞“ s200”
2.字符串的末尾不能為“ sping”,“ js”,“ json”,“ css”

這是我拿到的怪物,不起作用

(?=^.*$(?<!sping)(?<!js)(?<!css)(?<!json))(?=s200)

我是regex的新手,將不勝感激!

首先,您的正則表達式不匹配任何內容,因為您的正則表達式中只有環顧四周。

?=           # look ahead for match
?<!          # negative look behind

換句話說,您沒有匹配任何內容,而正則表達式則是在字符串中尋找position

說明:

(?=              # pos. lookahead
 ^.*$            # read anything
                 # and AFTER reading everything, check
 (?<!sping)      # if you have NOT read sping
 (?<!js)         # if you have NOT read js
 (?<!css)        # if you have NOT read css
 (?<!json)       # if you have NOT read json
)
(?=s200)         # from this position, check if there's "s200" ahead.

結論:您的正則表達式將永遠不會符合您的要求。

您可以使用一個正則表達式解決此問題,例如:

(.*)s200(.*)$(?<!css|js|json|sping)

這說

.*                       # read anything
s200                     # read s200
.*                       # read anything
$                        # match the end of the string
(?<!css|js|json|sping)   # negative lookbehind: 
                         # if you have read css,js,json or sping, fail

您可以分兩步完成此操作:

  • 首先檢查字符串是否包含帶有/s200/
  • 檢查字符串是否不以sping,js,json或/css|js(on)?|sping$/結尾/css|js(on)?|sping$/

您已將其標記為perl ,所以這是一個perl解決方案:

$_ = $stringToTest;
if (/s200/) {
    # We now know that the string contains "s200"
    if (/sping|json|js|css$/) {
        # We now know it end with one of sping,json,js or css
    }
}

暫無
暫無

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

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