Aman Virk
Aman Virk

Reputation: 3967

Javascript Confusing Regex Groups

I have regular expression which works great on regexr.com , but does not work with Javascript.

Here is the link to regexr http://regexr.com/3b780

Below is my Javascript attempt

      var expression="--user=foo:This is description"
      var regexExp = new RegExp("(?:=)(.[^:]+)|(?::)(.[^=]+)|(.[^=^:]+)","g");
      console.log(regexExp.exec(expression))

Which returns

[ '--user',
  undefined,
  undefined,
  '--user',
  index: 0,
  input: '--user=foo:This is description' 
]

Expected Output

[ '--user',
  'foo',
  'This is description',
  '--user',
  index: 0,
  input: '--user=foo:This is description' 
]

Upvotes: 1

Views: 52

Answers (1)

Ry-
Ry-

Reputation: 224855

RegExp#exec with a global regular expression needs to be called multiple times to get all matches. You can get closer with String#match (use a regular expression literal, by the way):

var expression = "--user=foo:This is description";
var re = /(?:=)(.[^:]+)|(?::)(.[^=]+)|(.[^=^:]+)/g;
console.log(expression.match(re));

which results in:

Array [ "--user", "=foo", ":This is description" ]

However, that’s a very unusual regular expression. The non-capturing groups are useless, the capturing groups are never part of the same match, and [^=^:] probably doesn’t have the intended effect. Maybe something like this, instead?

var re = /(--.+?)=(.+?):(.+)/;
var expression = "--user=foo:This is description";
console.log(re.exec(expression));

resulting in:

Array [ "--user=foo:This is description", "--user", "foo", "This is description" ]

Upvotes: 2

Related Questions