为特定子字符串创建带有“not”条件的正则表达式

Sri*_*i.S 3 regex

我有一个用例,我正在字符串中搜索特定的子字符串,如果该特定字符串包含另一个特定的子字符串,我希望它被拒绝。

前任:

  1. pikachu_is_the_best_ever_in_the_world_go_pikachu
  2. mew_is_the_best_ever_in_the_world_go_mew
  3. raichu_is_the_best_ever_in_the_world_go_raichu

我希望我的正则表达式能够选取包含单词“best”而不是单词“mew”的字符串,即第一个和第三个字符串。

我尝试将^(.*best).*$和组合^((?!mew).)*$到下面的表达式中,第二个正则表达式仅忽略字符串开头存在“mew”的单词。

^(.*best)((?!mew).).*$
Run Code Online (Sandbox Code Playgroud)

并且已经尝试过

^((?!mew).)(.*best).*$
Run Code Online (Sandbox Code Playgroud)

Tot*_*oto 8

  • Ctrl+F
  • 找什么:^(?=.*best)(?:(?!mew).)*$
  • 检查环绕
  • 检查正则表达式
  • 不要检查. matches newline
  • Search in document

解释:

^           : start of line
(?=         : positive lookahead
  .*        : 0 or more any character but newline
  best      : literally "best"
)           : end lookahead
(?:         : start non capture group
  (?!       : negative lookahead, make sure we don't have 
    mew     : literally "mew"
  )         : end lookahead
  .         : any character but newline
)*          : group may appear 0 or more times
$           : end of line
Run Code Online (Sandbox Code Playgroud)

  • @arieljannai:因为你需要匹配字符串中任何地方都没有`mew`,它从行的开头检查没有`mew`后跟1个字符,然后迭代(`*`)所有沿着绳子,直到绳子的末端。 (2认同)