正则表达式多个字符但没有特定字符串

编程入门 行业动态 更新时间:2024-10-24 07:22:16
本文介绍了正则表达式多个字符但没有特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下几行:

  • 可选:否",
  • 可选:两个非空白字符,
  • 几个非空白字符.

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

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 个单元测试):regex101/r/70soe2/1

Example online (4 unit tests): regex101/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.

查看正则表达式演示

更多推荐

正则表达式多个字符但没有特定字符串

本文发布于:2023-10-23 13:47:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字符串   字符   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!