开发者

JS Regex: Cannot use captures when using global?

开发者 https://www.devze.com 2023-01-29 04:21 出处:网络
It seems that I cannot use captures when using the global option? var regex = /^\\s*\\[(.*)\\]:\\s+(\\S+)(\\s+\"(.*)\"\\s*)?$/gm;

It seems that I cannot use captures when using the global option?

var regex = /^\s*\[(.*)\]:\s+(\S+)(\s+"(.*)"\s*)?$/gm;
var matches = textareaText.开发者_运维知识库match(regex);
for (var i in matches) {
  console.log(matches[i]);
}

I just get

match 0: [1]: http://google.com
match 1: [2]: http://test.com/example.png "hello world"

Without any captures like when I just use m swicth

match 0: [1]: http://google.com
match 1: 1
match 2: http://google.com
match 3: undefined
match 4: undefined
match index: 0
match input: [1]: http://google.com [2]: http://test.com/example.png "hello world"

But with just this, its just the 1st match, I want all. how can I do it?


Instead of using String.match, you can RegExp object's exec method and use regex.lastIndex to continue searching. Look here:

  • https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Here's a jsfiddle with a simple example:

  • http://jsfiddle.net/jqJDU/3/

Here's a separate example of lastIndex:

  • http://www.tutorialspoint.com/javascript/regexp_lastindex.htm
0

精彩评论

暂无评论...
验证码 换一张
取 消