正则表达式:数字与对捕获组的反向引用

Regex: a number vs. a backreference to a capture group

我一直在研究正则表达式,我正在为这个而摸不着头脑。在此页面 (https://www.regular-expressions.info/conditional.html) 上,我看到在条件正则表达式中,对编号反向引用的引用只是一个数字。例如,

(a)?b(?(1)c|d)

正则表达式如何知道我们不应该匹配数字“1”而不是对第一个捕获组的反向引用?之前在课程中我了解到反向引用将被转义,例如 \1、\2 等

根据您正在学习的正则表达式教程:

A special construct (?ifthen|else) allows you to create conditional regular expressions. If the if part evaluates to true, then the regex engine will attempt to match the then part. Otherwise, the else part is attempted instead. The syntax consists of a pair of parentheses. The opening bracket must be followed by a question mark, immediately followed by the if part, immediately followed by the then part. This part can be followed by a vertical bar and the else part. You may omit the else part, and the vertical bar with it.

或者,您可以在 if 部分检查 捕获组 到目前为止是否参加了比赛。 将捕获组的编号放在括号内,并将其用作 if 部分。

你的第二个问题是:

RegEx Demo of \b(a)?b(?(1)c|d)\b

请注意,我添加了单词边界以避免部分匹配 abd 之类的字符串。

What if someone actually wanted to match the literal 1 this way?

valid input: 1c or d invalid input: 1d

那就是:

\b(1)?(?(1)c|d)\b