简体   繁体   中英

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' 
]

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();

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" ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM