-3

I am studying regexp, there are examples. What's the different of g1 and 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"]
LYan
  • 1
  • 3

1 Answers1

0

A bunch of upper- and lowercase letters followed by space and that exact bunch second time. For example: UserName UserName or jnDJkjLKSdcSJ jnDJkjLKSdcSJ.

The difference is that g1 doesn't match the repetition of this bunch, because there is no \1 in it.


Clarified:

/\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
(picture is clickable)

Dima Parzhitsky
  • 3,716
  • 2
  • 20
  • 37
  • It would be nice to provide information such as (1) what the `\1` is called (2) and a link to documentation. –  Dec 18 '15 at 05:25