正则表达式中$ 1,$ 2等是什么意思?

问题描述:

我一次又一次地看到代码中使用了$ 1和$ 2。这是什么意思?你可以包括例子吗?

Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?

当你创建一个正则表达式时,你可以选择捕获部分匹配并保存它们作为占位符。它们的编号从 $ 1 开始。

When you create a regular expression you have the option of capturing portions of the match and saving them as placeholders. They are numbered starting at $1.

例如:

/A(\d+)B(\d+)C/

这将从 A90B3C 中捕获值 90 3 。如果您需要分组但不想捕获它们,请使用(?:...)版本而不是(... )

This will capture from A90B3C the values 90 and 3. If you need to group things but don't want to capture them, use the (?:...) version instead of (...).

数字从括号打开的顺序从左到右开始。这意味着:

The numbers start from left to right in the order the brackets are open. That means:

/A((\d+)B)(\d+)C/

匹配相同的字符串将捕获 90B 90 3

Matching against the same string will capture 90B, 90 and 3.