Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?
我一次又一次地看到代码中使用了1美元和2美元。这是什么意思?你能举好一些例子吗?
2 个解决方案
#1
31
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
.
创建正则表达式时,您可以选择捕获匹配的部分并将其保存为占位符。它们的编号从1美元起。
For instance:
/A(\d+)B(\d+)C/
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 (...)
.
这将从A90B3C捕获值90和3.如果您需要对事物进行分组但不想捕获它们,请使用(?:...)版本而不是(...)。
The numbers start from left to right in the order the brackets are open. That means:
数字从括号打开的顺序从左到右开始。这意味着:
/A((\d+)B)(\d+)C/
Matching against the same string will capture 90B
, 90
and 3
.
匹配相同的字符串将捕获90B,90和3。
#2
6
This is esp. useful for Replacement String Syntax (i.e. Format Strings) Goes good for Cases/Case Foldings for Find & Replaces. To reference a capture, use $n where n is the capture register number. Using $0 means the entire match. Example : Find: (<a.*?>)(.*?)(</a>) Replace: $1\u$2\e$3
这是特别的。对替换字符串语法(即格式字符串)有用,适用于查找和替换的案例/案例折叠。要引用捕获,请使用$ n,其中n是捕获寄存器编号。使用$ 0表示整场比赛。示例:查找:( )(。*?)()替换:$ 1 \ u $ 2 \ e $ 3 。*?>
#1
31
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
.
创建正则表达式时,您可以选择捕获匹配的部分并将其保存为占位符。它们的编号从1美元起。
For instance:
/A(\d+)B(\d+)C/
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 (...)
.
这将从A90B3C捕获值90和3.如果您需要对事物进行分组但不想捕获它们,请使用(?:...)版本而不是(...)。
The numbers start from left to right in the order the brackets are open. That means:
数字从括号打开的顺序从左到右开始。这意味着:
/A((\d+)B)(\d+)C/
Matching against the same string will capture 90B
, 90
and 3
.
匹配相同的字符串将捕获90B,90和3。
#2
6
This is esp. useful for Replacement String Syntax (i.e. Format Strings) Goes good for Cases/Case Foldings for Find & Replaces. To reference a capture, use $n where n is the capture register number. Using $0 means the entire match. Example : Find: (<a.*?>)(.*?)(</a>) Replace: $1\u$2\e$3
这是特别的。对替换字符串语法(即格式字符串)有用,适用于查找和替换的案例/案例折叠。要引用捕获,请使用$ n,其中n是捕获寄存器编号。使用$ 0表示整场比赛。示例:查找:( )(。*?)()替换:$ 1 \ u $ 2 \ e $ 3 。*?>