[英]Regex to check for everything except a string
我正在嘗試編寫一個正則表達式以匹配除包含“ domain.com/file/”的字符串以外的所有內容。
因此,如果給我一個URL,我想確保它不包含“ domain.com/file/”。
我知道這可能超級簡單,但是我對正則表達式不滿意。
您可以為此使用strstr
而不是正則表達式。 它的名稱不正確,但是如果找不到字符串,它將返回false
。 確保使用===
而不是==
因為字符串將具有真實值。
除非您的問題不夠具體,否則您實際上並不需要正則表達式的功能。
在回顧了幾件事之后,似乎strpos
實際上比strstr
更快。 您肯定需要使用===
代替此功能使用==
。
來自PHP文檔的strpos
示例:
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
使用不區分大小寫的匹配的示例:
if (stristr($input, 'domain.com/file/') === false) {
// not found.
}
只需使用! 作為正則表達式中的NOT運算符
$pattern = '#!domain\.com/file/#';
if(preg_match($pattern,$data)){
}
還可以回答正則表達式問題:為此,您可以使用(?!...)
否定斷言 :
if (preg_match("~(?!.*domain.com/file/)~", $string))
如果將其與其他比較結合使用,這是有道理的。 單靠否定preg_match
結果會更明智。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.