正则表达式多个字符但没有特定字符串
Regex multiple characters but without specific string
我的行包括:
- 可选:“否”,
- 可选:两个非空白字符,
- 几个非空白字符。
我想从包含以下内容的每一行中捕获字符串:
- 可选:两个非空白字符(但不是“无”部分),
- 几个非空白字符。
示例行:
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
+ 空格部分。
最好在开头使用一个non-capturing可选组:
^
(?: 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
)
$
(?:no \s \K)?
中的\K
将从匹配值中省略消耗的字符串部分,您将得到预期的结果作为一个整体匹配值。
我的行包括:
- 可选:“否”,
- 可选:两个非空白字符,
- 几个非空白字符。
我想从包含以下内容的每一行中捕获字符串:
- 可选:两个非空白字符(但不是“无”部分),
- 几个非空白字符。
示例行:
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
+ 空格部分。
最好在开头使用一个non-capturing可选组:
^
(?: 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
)
$
(?:no \s \K)?
中的\K
将从匹配值中省略消耗的字符串部分,您将得到预期的结果作为一个整体匹配值。