regex - 正则表达式多个字符但没有特定字符串
问题描述
我的行包括:
- 可选:“否”,
- 可选:两个非空白字符,
- 几个非空白字符。
我想从每一行中捕获字符串,其中包括:
- 可选:两个非空白字符(但不是“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
字符串的可选 + 空格部分。
最好在开始时使用非捕获可选组:
^
(?: 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
)
$
\K
in将(?:no \s \K)?
省略匹配值中消耗的字符串部分,您将获得预期的结果作为整个匹配值。
查看正则表达式演示
推荐阅读
- php - 检查数组中的元素是否是 Laravel Validator 中另一个数组中的元素
- python - 根据熊猫中的条件获取列名
- python - 从 csv 文件循环 url 以使用 python 抓取 html
- javascript - react中动态添加字段的表单验证
- concurrency - 预置并发不会使 AWS Lambda 函数保持温暖
- javascript - 如何通过链接传递其状态在一个组件中设置的对象的属性并将它们呈现在 React 的另一个组件中
- perl - RPi::Pin 对象——它们可以被销毁吗?这样可以创建另一个使用该引脚的人吗?
- reactjs - 如何获取单选按钮值并将其上传到 Firebase?
- angular - Angular,Promises:在批处理完成之前不要返回承诺
- android - E/LoadedApk:无法仅在 Android Q (API 29) 上实例化 appComponentFactory