什么/ \ b([a-zA-Z] +)\ 1 \ b / gi在Javascript RegExp中的含义

时间:2015-12-18 02:10:54

标签: javascript regex

我正在学习regexp,有例子。 g1和g2有什么不同?

var g1 = /\b([a-zA-Z]+) \b/gi.exec("Is is this is a the cost of of gas going up?");
var g2 = /\b([a-zA-Z]+) \1\b/gi.exec("Is is this is a the cost of of gas going up?");

console.log(g1);      // result is ["Is ", "Is", index: 0"]
console.log(g2);      // result is ["Is is", "Is", index: 0"]

1 个答案:

答案 0 :(得分:0)

一堆大写和小写字母后面跟着空格,第二次是精确的串。例如:UserName UserNamejnDJkjLKSdcSJ jnDJkjLKSdcSJ

区别在于g1与这一群的重复不匹配,因为其中没有\1

<强>澄清

  

/\b([a-zA-Z]+) \b/gi

/       start regexp
\b      match a word boundary
(…)     create a capturing group
[…]     create a class of characters to match one of them
a-z     match any character between "a" and "z" ("a", "b", "c", "d", "e" …)
A-Z     match any character between "A" and "Z" ("A", "B", "C", "D", "E" …)
+       match one or more of a preceding token (see above)
        match space sign (exactly)
\1      match first capturing group
\b      match a word boundary
/gi     finish regexp and set flags "global" and "case-insensitive"

\b([a-zA-Z]+) \b

Regular expression visualization
(图片可点击)

相关问题