2016-03-28 61 views
0

我必須匹配單詞'like'而在它之前沒有單詞'not'。在下面的例子中,'like'之前有一個'not',所以它不應該匹配它。我將如何解決這個問題?將正則表達式匹配不帶任何單詞落在另一個單詞之後

$tempInput = "i do not like to fail"; 
if (preg_match("~(?!not)(like)~", $tempInput, $match)) { 

print_r($match); 

} 

結果:

陣列([0] =>如[1] =>等)

需要結果:

+0

從'like'這個詞你是否需要在**或**之後尋找**以檢查在那裏是否沒有'not'? – Rizier123

+1

使用負反向: '「〜(?<!)不喜歡〜」'(或帶有單詞邊界:''〜(?<!\ bnot)\ blike \ b〜'') –

+0

@ Rizier123 。 – frosty

回答

2

negative lookbehind對於文字字符串not這樣做會做。

正則表達式:/(?<!not)like/

說明:

  • (?<!not)look behind,並檢查是否有字not。如果不存在則like將被匹配。

Regex101 Demo

1

這裏有一個小正則表達式魔術

使用固定寬度的lookbehind斷言很容易限制。
例如,noob的正則表達式(?<!not)like匹配not like無效窗體的
整天(不好)。

但是這個(?<!not)(?<!\s)\s*\b(like)將匹配,就像一個變量
長度lookbehind在php中是合法的。

在一個理想的世界中,它會是這個(?<!not\s+)like變量。

所以,我留給任何人想知道它是如何工作的。
like字始終在捕獲組1

作爲獎勵的like基團可以是任何正則表達式的子表達。

(?<! not)  # Guard, Not 'not' behind 
(?<! \s)   # Guard, Not whitespace behind 
\s*    # Optional whitespace that can't be backtracked 
\b    # Word boundary 
(like)   # (1), 'like' 
相關問題