繁体   English   中英

Preg_match从文本中排除单词

[英]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

查看live demo

正则表达式:

^              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

这个例子

使用的正则表达式是

/firstword((?!wrongword).)*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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM