[英]Preg_match exclude word from text
我有字符串:
FirstWord word2 word3 wrongWord word4 lastWord
想要用FirstWord
選擇字符串開頭,以lastWord
並且不包含wrongWord
。
我有第一個也是最后一個:
/ firstword(。*?)lastword / i
但排除wrongword
不起作用。
嘗試:
/ firstword(^ wrongWord *?)lastword / i
/ firstword ^((?! wrongWord)。)* lastword / i
更像這樣,但沒有任何作用。
簡單的以下是什么問題?
/^firstword ((?:(?!wrongword).)+) lastword$/i
正則表達式:
^ the beginning of the string
firstword 'firstword '
( group and capture to \1:
(?: group, but do not capture (1 or more times)
(?! look ahead to see if there is not:
wrongword 'wrongword'
) end of look-ahead
. any character except \n
)+ end of grouping
) end of \1
lastword ' lastword'
$ before an optional \n, and the end of the string
你可以使用這個技巧:
/^firstword ((?:[^w]+?|\Bw|w(?!rongword\b))*?) lastword$/i
或更有效:
/^firstword ((?>[^w\s]++|\s(?!lastword$)|\Bw|w(?!rongword\b))*+) lastword$/i
如果禁止的詞恰好是更長詞的一部分怎么辦? 例如,如果您希望字符串以“first”開頭並以“last”結尾但不包含單詞“word”,該怎么辦? 例如:
"first one two word last" # don't match
"first three wordplay four last" # OK
"first five swordfish six seven last" # OK
調整接受的答案會給你這樣的:
/^first (?:(?!word).)+ last$/i
......但這會拒絕所有三個字符串。 無論如何,無需在每個位置執行前瞻。 只需在每個單詞的開頭處執行一次:
/^first(?:\s+(?!word\b)\w+)*\s+last$/i
查看現場演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.