首页 > 解决方案 > 正则表达式多个字符但没有特定字符串

问题描述

我的行包括:

我想从每一行中捕获字符串,其中包括:

示例行:

ab123
ab 123
no abc123
no ab 123

我想捕捉:

ab123
ab 123
abc123
ab 123

我的正则表达式(仅适用于没有“no”的示例)。

^
  (?! no \s) # not "no "
  ( # match it
    (?: \S{1,2} \s )? # optional: 1-2 non whitespace characters and one space, BUT NOT GET "no " (it doesn't works)
    \S+ # non whitespace characters
  )
$

在线示例(4 个单元测试):https ://regex101.com/r/70soe2/1

也许我应该以某种方式使用负面展望(?! no \\s)或负面展望?(?<! no \\s)但我不知道如何使用它。

标签: regexregex-lookarounds

解决方案


您实际上不能在这里依赖环视,您需要使用no字符串的可选 + 空格部分。

最好在开始时使用非捕获可选组

^
  (?: no \s)? # not "no "
  ( # capture it
    (?: \S{1,2} \s )? # optional: 1-2 non whitespace characters and one space, BUT NOT GET "no " (it doesn't works)
    \S+ # non whitespace characters
  )
$

查看正则表达式演示

您需要的值在第 1 组内。

如果您的正则表达式引擎支持\K构造,您可以改用它:

^
  (?:no \s \K)? # not "no "
  ( # match it
    (?: \S{1,2} \s )? # optional: 1-2 non whitespace characters and one space, BUT NOT GET "no " (it doesn't works)
    \S+ # non whitespace characters
  )
$

\Kin将(?:no \s \K)? 省略匹配值中消耗的字符串部分,您将获得预期的结果作为整个匹配值。

查看正则表达式演示


推荐阅读