【问题标题】:Can we rewrite lookbehind in terms of the if-then-else?我们可以根据 if-then-else 重写lookbehind 吗?
【发布时间】:2014-06-10 02:08:02
【问题描述】:

给定两个正则表达式 expr1expr1,我们可以根据 if-then-else 构造等效地编写一个后向 (?<=expr1)expr2 吗?

例如,后面的(?<=expr1)expr2 是否等同于(expr1)(?(-1)expr2|expr3),其中expr3 是一些永远不可能匹配的正则表达式?

也就是说,这两个正则表达式的(?<=expr1)expr2(expr1)(?(-1)expr2|expr3) 描述的一样吗?

如果是,如何选择expr3,这样就永远无法匹配?

谢谢?

【问题讨论】:

  • @Dalorzo:(?(-1)...|...) 是一个条件,用于测试最后定义的捕获组是否存在。
  • 什么书?顺便说一句,我给了你链接。 @Dalorzo
  • @Tim 查看问题其他部分的更新。

标签: regex


【解决方案1】:

执行两个正则表达式的 (?

没有。它们匹配不同的字符串。

(?<=expr1)expr2 只能匹配一件事:expr2,而不仅仅是任何地方:expr1expr2 中的 expr2

相比之下,(expr1)(?(-1)expr2|expr3) 只能匹配:expr1expr2

显然,expr2expr1expr2 是不同的字符串。答案是不。

..但另一个答案是肯定的:

Can we write a lookbehind (?<=expr1)expr2 equivalently in terms of the if-then-else construct?

是的。这在 an-then-else 中使用(隐含 else):(?(?<=expr1)expr2),它也匹配 expr1expr2。当然,它也使用了lookbehind。

“隐含的 else”听起来不合适?添加|,如(?(?<=expr1|)expr2)

expr3 呢?

您最后一个正则表达式(expr1)(?(-1)expr2|expr3) 将永远无法匹配expr3。如果您希望它有机会,则必须将捕获组设为可选:(expr1)?(?(-1)expr2|expr3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多