2017-09-14 64 views
0

我想有一個正則表達式模式匹配的行:
1,本行必須包含字符串的末尾不能「單詞「S200」
2.消費滿」,‘爵士’,‘JSON’,‘CSS’正則表達式來排除模式,但包括圖案

這裏是一個怪物我,不工作

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

我是新來的正則表達式,任何幫助,將aapreciated !

+0

這_must_是正則表達式? –

+0

'(?s)^(?!sping $)(?!js $)(?! css $)(?! json $)(?= s200)' –

回答

1

對於初學者來說,你的正則表達式不匹配任何東西,因爲你只有你的正則表達式。

?=   # 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與/s200/
  • 檢查是否字符串不以消費滿,JS,JSON或JSON結束與/css|js(on)?|sping$/
1

您已經標記這是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 
    } 
} 
+0

您應該解釋爲什麼OP的工作不起作用,因爲這是個問題。 –