Javascript $1、$2 等在正则表达式中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5982824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does $1, $2, etc. mean in Regular Expressions?
提问by david
Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?
我一次又一次地看到 $1 和 $2 在代码中被使用。这是什么意思?你能包括例子吗?
采纳答案by tadman
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
。
回答by closebrace
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
这是 esp。对替换字符串语法(即格式字符串)很有用 适用于查找和替换的案例/案例折叠。要引用捕获,请使用 $n,其中 n 是捕获寄存器编号。使用 $0 表示整个匹配。例子 : Find: (<a.*?>)(.*?)(</a>) Replace: $1\u$2\e$3