官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 涿鹿县| 湾仔区| 馆陶县| 寿光市| 休宁县| 连江县| 土默特右旗| 阿拉善右旗| 阳曲县| 天峻县| 平和县| 托里县| 余江县| 凌海市| 灌阳县| 朝阳县| 平舆县| 平凉市| 古田县| 开江县| 呼玛县| 南城县| 沙洋县| 岳普湖县| 遂昌县| 登封市| 涿州市| 肇源县| 平顶山市| 苗栗市| 故城县| 宁阳县| 措美县| 嘉义市| 黄陵县| 二手房| 承德市| 静宁县| 榕江县| 新津县| 上饶县|