- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 254字
- 2021-07-09 19:07:34
Backreferences
After an expression is evaluated, each group is stored for later use. These values are known as backreferences. Backreferences are created and numbered by the order in which opening parenthesis characters are encountered going from left to right. You can think of backreferences as the portions of a string that are successfully matched against terms in the regular expression.
The notation for a backreference is a backslash followed by the number of the capture to be referenced, beginning with 1, such as \1
, \2
, and so on.
An example could be /^([XYZ])a\1/
, which matches a string that starts with any of the X
, Y
, or Z
characters followed by an a
and followed by whatever character matched the first capture. This is very different from /[XYZ] a[XYZ]/
. The character following a
can't be any of X
, or Y
, or Z
, but must be whichever one of those that triggered the match for the first character. Backreferences are used with String's replace()
method using the special character sequences, $1
, $2
, and so on. Suppose that you want to change the 1234 5678
string to 5678 1234
. The following code accomplishes this:
var orig = "1234 5678"; var re = /(\d{4}) (\d{4})/; var modifiedStr = orig.replace(re, "$2 $1"); console.log(modifiedStr); //outputs "5678 1234"
In this example, the regular expression has two groups each with four digits. In the second argument of the replace()
method, $2
is equal to 5678
and $1
is equal to 1234
, corresponding to the order in which they appear in the expression.
- 深度實(shí)踐OpenStack:基于Python的OpenStack組件開發(fā)
- Visual Studio 2012 Cookbook
- 算法訓(xùn)練營:入門篇(全彩版)
- Python金融數(shù)據(jù)分析
- ArcGIS By Example
- Linux Device Drivers Development
- The Complete Coding Interview Guide in Java
- AIRIOT物聯(lián)網(wǎng)平臺(tái)開發(fā)框架應(yīng)用與實(shí)戰(zhàn)
- Android應(yīng)用開發(fā)實(shí)戰(zhàn)
- jQuery從入門到精通(微課精編版)
- Akka入門與實(shí)踐
- Java程序設(shè)計(jì)實(shí)用教程(第2版)
- Beginning C# 7 Hands-On:The Core Language
- 信息學(xué)奧林匹克競賽初賽精講精練
- Elasticsearch實(shí)戰(zhàn)(第2版)