这个正则表达式是什么意思?

7

我需要知道的是:

  1. (?( 的含义是什么?
  2. ?: 的含义是什么?

我正在尝试理解以下正则表达式:

(请注意上述符号在以下正则表达式中的使用)

(?(?=and )(and )|(blah))(?:[1][9]|[2][0])[0-9][0-9]

作为起点,请查看这个正则表达式速查表 - nickhar
是的,我是。是的,我是。在C#中尝试使用此字符串,它将被接受。 - harshit
提醒一下未来的你:在代码中的任何正则表达式上方添加注释(可以附带示例),以避免未来出现此类问题。正则表达式往往是难以阅读的“只写”代码,如果你不是每天都在做这些事情,就会感到困难。 - Oliver
@Oliver,由于这个正则表达式不是我写的,我需要理解并对其进行更改,所以我不得不发布它。此外,我不习惯每天这样做。 - harshit
@harshit:但请将您对正则表达式代码的理解作为注释添加,这样下一个程序员就不必在网上搜索解释了。 - Oliver
@Oliver 注意了。 - harshit
4个回答

3

(?(?=and )(and )|(blah)) 模式类似于 if-then-else 条件语句,即 (?(expression)yes|no)。如果存在 and,则匹配and,否则匹配blah

(?:) 是一个非捕获组,它不会被包含在组中或用作反向引用\1。

因此,

(?(?=and )(and )|(blah))(?:[1][9]|[2][0])[0-9][0-9]

匹配
and 1900
blah2000
and 2012
blah2013

注意(这一切都与分组有关)

可以使用以下正则表达式实现相同的效果 (and |blah)(?:[1][9]|[2][0])[0-9][0-9]。 这些正则表达式之间唯一的区别在于所形成的组数。

因此,我的正则表达式将形成一个包含 andblah 的组。

你的正则表达式不会形成任何组。只有当匹配到blah时它才会形成一组。


你能用简单易懂的英语解释一下吗?我的意思是为什么有两个and?我已经阅读了其他答案中给出的链接,但我还是无法理解。 - harshit

2
以下是一些模式的快速参考:
.   Any character except newline.
\.  A period (and so on for \*, \(, \\, etc.)
^   The start of the string.
$   The end of the string.
\d,\w,\s    A digit, word character [A-Za-z0-9_], or whitespace.
\D,\W,\S    Anything except a digit, word character, or whitespace.
[abc]   Character a, b, or c.
[a-z]   a through z.
[^abc]  Any character except a, b, or c.
aa|bb   Either aa or bb.
?   Zero or one of the preceding element.
*   Zero or more of the preceding element.
+   One or more of the preceding element.
{n} Exactly n of the preceding element.
{n,}    n or more of the preceding element.
{m,n}   Between m and n of the preceding element.
??,*?,+?,
{n}?, etc.  Same as above, but as few as possible.
(expr)  Capture expr for use with \1, etc.
(?:expr)    Non-capturing group.
(?=expr)    Followed by expr.
(?!expr)    Not followed by expr.

表达式(?(?=and )(and )|(blah))是一个if-else表达式。

您可以在此处测试正则表达式:Regexpal.com


2
(?:...)

是一个非捕获。它与(...)的作用类似,但不会创建后续重复使用的反向引用(\1等)。

(?(condition)true|else)

是一个条件语句,它试图匹配condition;如果成功,它将尝试匹配true,否则它将尝试匹配else

这是一个很少见的正则表达式结构,因为它没有太多使用案例。在您的情况下,

(?(?=and )(and )|(blah))

可以重写为

(and |blah)

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接