【问题标题】:Regex multiple characters but without specific string正则表达式多个字符但没有特定字符串
【发布时间】:2020-09-10 14:12:32
【问题描述】:

我的行包括:

  • 可选:“否”,
  • 可选:两个非空白字符,
  • 几个非空白字符。

我想从包含以下内容的每一行中捕获字符串:

  • 可选:两个非空白字符(但不是“no”部分),
  • 几个非空白字符。

示例行:

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)?但是我不知道怎么用。

【问题讨论】:

  • 使用捕获方法,^(?:no\s)?((?:\S{1,2}\s)?\S+)$,参见regex101.com/r/XcntiK/1。或者,使用\K(?:no \s \K)?。见regex101.com/r/70soe2/2
  • 我有更复杂的正则表达式,我已经隔离了我的问题。我的应用程序是“基于正则表达式的”。我试图学会消极地看待背后(regular-expressions.info/lookaround.html),但我不能将其应用于这种情况。顺便说一句,这将是我的教育目标。
  • 谢谢,(?:no\s)? 它有效!没有消极的展望。

标签: regex regex-lookarounds


【解决方案1】:

您实际上不能在这里依赖环视,您需要使用可选的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
  )
$

regex demo

您需要的值在第 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
  )
$

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

regex demo

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 2021-09-06
    • 2021-03-05
    • 1970-01-01
    • 2022-11-16
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多