2016-11-28 40 views
0

給定字符串python php ruby javascript jsonp perhapsphpisoutdated,如何過濾包含p但不包含ph的文字?如何檢查使用正則表達式的文字

我寫這個正則表達式:

var reg = /\b\w*p(?!h)\w*\b/; 

然而,上面還匹配像phpph****p**字,所以它不準確?我應該如何編寫正則表達式?

+0

'str.split('').filter(x => x.includes('p')&&!x.includes('ph'))' – adeneo

+1

共識是[「給我一個X的正則表達式」問題應該關閉](http://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed)。 – lexicore

回答

0

您可以通過使用向前看符號做到這一點:

(?=\w*p)(?!\w*ph)\b(\w+)\b 

Regex101 Example

Regular Expression Resource


擊穿

\b(\w+)\b // Looks for word characters (\w) separated by word boundaries 
(?=\w*p) // Asserts each word found contains a "p" (positive lookahead) 
(?!\w*ph) //Asserts each word found does not contain "ph" (negative lookahead) 
+0

非常感謝! – Perhaps

相關問題