簡體   English   中英

如何在Perl中的匹配正則表達式中包含變量,並檢查變量是否在字符串中?

[英]How can I include a variable in a match regular expression in Perl, and check if the variable is NOT in the string?

我想在Perl中的匹配常規rexpression中包含一個變量,並檢查該變量是否在字符串中。

這里的鏈接指示如何包含變量,但是如果變量不匹配,我將難以測試。 當然,我可以像這樣否定if條件:

if (!($string =~ m/$Myvar/)) {
# Do some code here
}

但我確信在正則表達式匹配中必須有辦法。 有任何想法嗎?

提前謝謝你的幫助。

使用!~運算符。

if ($string !~ m/$Myvar/) {
# Do some code here
}

或者使用index並完全避免使用正則表達式引擎。 即使$Myvar具有正則表達式引擎專門處理的字符,這也會起作用。

if ( index($string, $Myvar) < 0 ) {
# Do some code here
}

否定結果有什么問題?

“負面匹配”(需要一個負面的先行斷言 )會使你的正則表達式更加復雜:

if ($string =~ m/^(?!.*$Myvar)/s) {
    # Do some code here
}

暫無
暫無

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

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