正则表达式匹配中间不在列表中?

Regex match middle not in a list?

我正在尝试匹配第一个和最后一个字符之间不包含某些字符串的字符串。这些字符串以列表的形式出现,这里是:

this
is
a
demo

可以有更多。我写了

1(?!this|is|a|demo).*2

这里是my regex live demo。它只匹配 1demo12,我也需要它匹配 1demoo2

更多测试用例:

1this2       # do not want match
1is2         # do not want match
1a2          # do not want match
1demo2       # do not want match
1demoo2      # want match
1demo12      # want match

我尝试使用 Negative Lookahead 但失败了。

您可以使用

^1(?!(?:this|is|a|demo)2$).*2$

参见regex demo

详情:

  • ^ - 字符串开头
  • 1 - 一个 1 字符
  • (?!(?:this|is|a|demo)2$) - 如果有 thisisademo 后跟 [=19=,则匹配失败的否定前瞻] 和紧接在当前位置右侧的字符串结尾
  • .* - 除换行字符外的任何零个或多个字符,尽可能多
  • 2 - 一个 2 字符
  • $ - 字符串结尾。