1

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' 
]
Aman Virk
  • 3,909
  • 8
  • 40
  • 51
  • 4
    What is it supposed to do? Are you sure you want to capture three groups as three different matches? (It’s why the spacing is unusual on your regexr output.) – Ry- Jun 16 '15 at 06:17
  • 1
    What's your expected output? – Avinash Raj Jun 16 '15 at 06:21

1 Answers1

2

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" ]
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Okay make sense , if it has multiple groups , then we need to re execute multiple times. – Aman Virk Jun 16 '15 at 06:31
  • Can you please explain what is the flow of `/(--.+?)=(.+?):(.+)/` – PHP dev Jun 16 '15 at 06:48
  • 1
    (--.+?) Get anything starting with -- , and capture it in a group until = and same goes on for all other groups – Aman Virk Jun 16 '15 at 06:54
  • Actually dot(.) is used for getting any single character match only na ji....here what is the use of `.+?` – PHP dev Jun 16 '15 at 06:57
  • 1
    ? is for 0 or 1 , + is for 1 or more , we can also use * instead of +? , which means 0 or more – Aman Virk Jun 16 '15 at 07:01
  • 1
    @papsk: `?` after a quantifier like `+` indicates a non-greedy match. It will match as few characters as possible. For example, `(a+?)(a+)` will capture `a` and `aa` in `aaa`, and `(a+)(a+)` will capture `aa` and `a`. – Ry- Jun 16 '15 at 07:03
  • @minitech so will `(.+?):(.+)` capture `.`? – PHP dev Jun 16 '15 at 07:09