正则表达式,仅当子串在字符串中时匹配,而子串不在

时间:2018-05-17 19:44:40

标签: regex

所以我试着写一个正则表达式,由于某种原因我不能让它正常工作。

如果string1在字符串中,而不是字符串2,我尝试做的是匹配。

实施例

fault            shouldn't match
bucket           should match
fault bucket     shouldn't match
bucket fault     shouldn't match
true bucket      should match
bucket true      should match

到目前为止我能够来的壁橱是这个...这将匹配任何时候字符串中有桶,但如果故障在字符串中也将匹配

(?!fault)bucket

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用此否定前瞻性正则表达式:

^(?!.*\bfault\b).*\bbucket\b

RegEx Demo

  • 如果在行中的任何位置找到完整的单词(?!.*\bfault\b),则否定前瞻表达式fault将无法匹配
  • .*\bbucket\b
  • 行的任何位置匹配bucket
  • \b用于字边界