正则表达式多个字符但没有特定字符串 [英] Regex multiple characters but without specific string
问题描述
我有以下几行:
- 可选:否",
- 可选:两个非空白字符,
- 几个非空白字符.
我想从包含以下内容的每一行中捕获字符串:
I want to capture string from each line which consist of:
- 可选:两个非空白字符(但不是无"部分),
- 几个非空白字符.
示例行:
ab123
ab 123
no abc123
no ab 123
我想捕捉:
ab123
ab 123
abc123
ab 123
我的正则表达式(仅适用于没有no"的示例).
My regexp (works only for examples without "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
Example online (4 unit tests): https://regex101.com/r/70soe2/1
也许我应该以某种方式使用否定前瞻(?! no \\s)
或否定(?<! no \\s)
?但是不知道怎么用.
Maybe should I use negative look ahead (?! no \\s)
or negative look behind (?<! no \\s)
in some way? But I don't know how to use it.
推荐答案
在这里你不能真正依赖环视,你需要使用可选的 no
+ 字符串的空白部分.
You cannot actually rely on lookarounds here, you need to consume the optional no
+ whitespace part of the string.
最好在开始时使用非捕获可选组:
^
(?: 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 组内.
The value you need is inside Group 1.
如果您的正则表达式引擎支持 \K
构造,您可以使用它来代替:
If your regex engine supports \K
construct, you may use this instead:
^
(?: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
将省略匹配值中消耗的字符串部分,您将得到预期的结果一个完整的匹配值.
The \K
in (?:no \s \K)?
will omit the consumed string part from the match value, and you will get the expected result as a whole match value.
查看正则表达式演示
这篇关于正则表达式多个字符但没有特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!