正则表达式,带有可选部分和负前瞻 [英] Regular expression with optional part and negative lookahead

查看:60
本文介绍了正则表达式,带有可选部分和负前瞻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查字符串是否包含模式:以"A"开头,后跟零个或多个空格,然后是除"B"以外的任何内容.

I need check if a string contains the pattern: starts with "A" followed by zero or more spaces and then anything but not "B".

因此,以下内容必须匹配:"A" ."AX" "A X" "A" "A XB"

So, the following must match: "A". "AX", "A X", "A ", "A XB"

以下字符串不能匹配:"AB" "A B"

The following strings must not match: "AB", "A B"

我的天真尝试是 A \ s *(?! B),但它与不受欢迎的"A B" 匹配.

My naive attempt was A\s*(?!B), but it matches the undesirable "A B".

推荐答案

如果只需要输入true或false,则可以将 \ s * 放入前行:

If you just need to get true or false, you may put the \s* into the lookahead:

Regex.IsMatch(s, @"A(?!\s*B)")

它将找到没有0+空格的 A ,后跟 B .

It finds A that has no 0+ whitespaces followed with B after it.

请参见在您的模式 A \ s *(?! B)中,可以在任何0+空格之后执行负向超前查找,并且一旦空格后面没有 B ,将返回有效的匹配项(由于使用 \ s * 量化模式而可能发生的回溯).

In your pattern, A\s*(?!B), the negative lookahead can be executed after any 0+ whitespaces, and once a whitespace not followed with B is found, a valid match is returned (that happens due to backtracking that is possible thanks to \s* quantified pattern).

如果您需要真正匹配 A 和它后面的空格,但是如果这些空格后面没有 B ,请使用我的注释中的模式.

If you need to actually match the A and the whitespace after it, but if these whitespaces are not followed with B, use the pattern from my comment.

(?>A\s*)(?!B)

此模式匹配:

  • (?> A \ s *)-一个原子组,匹配 A ,然后匹配0+个空格,且没有回溯到组模式中允许
  • (?! B)-空格后没有 B ,否则整个匹配失败.
  • (?>A\s*) - an atomic group, matches A, then 0+ whitespaces with no backtracking into the group pattern allowed
  • (?!B) - no B after the spaces, or the whole match is failed.

这篇关于正则表达式,带有可选部分和负前瞻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆