这个正则表达式意味着什么

时间:2012-10-17 11:12:09

标签: c# regex

我真正需要知道的是:

  1. (?(是什么意思?
  2. ?:是什么意思?
  3. 我想弄清楚的正则表达式是:

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

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

4 个答案:

答案 0 :(得分:2)

使用

(?(?=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时它才会组成一个组。

答案 1 :(得分: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表达式:)

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

答案 2 :(得分:2)

(?:...)

是非捕获group。它的工作方式与(...)类似,但它不会创建反向引用(\1等)以供以后重复使用。

(?(condition)true|else)

conditional,它会尝试匹配condition;如果成功,则会尝试匹配true,否则会尝试匹配else

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

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

本可以改写为

(and |blah)

答案 3 :(得分:0)

?:是一个非捕获组。 (?ifthen|else)用于构造if,然后表达式。

您可以在此处详细了解这些内容。

http://www.regular-expressions.info/conditional.html

相关问题