简体   繁体   English

Javascript令人困惑的正则表达式组

[英]Javascript Confusing Regex Groups

I have regular expression which works great on regexr.com , but does not work with Javascript. 我有一个正则表达式,它在regexr.com上很好用,但不适用于Javascript。

Here is the link to regexr http://regexr.com/3b780 这是regexr的链接http://regexr.com/3b780

Below is my Javascript attempt 以下是我的Javascript尝试

      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 . 具有全局正则表达式的RegExp#exec 需要多次调用以获取所有匹配项 You can get closer with String#match (use a regular expression literal, by the way): 您可以更接近String#match (顺便说一下,使用正则表达式文字):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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