【发布时间】: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)?它有效!没有消极的展望。