CarbonMan
CarbonMan

Reputation: 4490

Javascript regex matching too many characters

My string is defined as;

var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var res = str.match(/\[\[(.*[^\]])\]\]/g)

I would like to extract "http://www.yahoo.com" and "more" but I am getting

[ '[[http://www.yahoo.com]] again [[more]]' ]

What should the regex be?

Upvotes: 0

Views: 162

Answers (3)

hwnd
hwnd

Reputation: 70722

Use the exec() method in a loop, pushing the match result of the captured group to the results array. Also, remove the dot . greedy operator * from your capturing group because it is not necessary since you use negation.

var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var re  = /\[\[([^\]]*)]]/g, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}
console.log(matches) //=> [ 'http://www.yahoo.com', 'more' ]

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

Putting ]] inside a negated character class won't give the result you want. Use inside a negative lookahead like below.

\[\[((?:(?!\]\]).)*)\]\]

DEMO

> var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
undefined
> var re = /\[\[((?:(?!\]\]).)*)\]\]/g;
undefined
> var matches = [];
undefined
> while (m = re.exec(str)) {
..... matches.push(m[1]);
..... }
2
> console.log(matches)
[ 'http://www.yahoo.com', 'more' ]

Upvotes: 2

Duniyadnd
Duniyadnd

Reputation: 4043

var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var res = str.match(/\[\[(.+?)\]\]/)
console.log(res[1]);

Upvotes: 0

Related Questions