Reputation: 315
I'm trying to match just the characters between some set characters using regex? I'm very new to this but I'm getting somewhere...
I want to match all instances of text between '[[' and ']]' in the following string:
'Hello, my [[name]] is [[Joffrey]]'.
So far I've been able to retrieve [[name
and [[Joffrey
with the following regex:
\[\[([^\]])*\g
I've experimented with grouping etc but can't seem to get the 'contents' only (name
and Joffrey
).
Any ideas?
Thanks
Upvotes: 3
Views: 4209
Reputation: 207
Here is the regex:
/\[\[(.*?)\]]/g
Explanation:
\[ Escaped character. Matches a "[" character (char code 91).
( Groups multiple tokens together and creates a capture group for extracting a substring or using a backreference.
. Dot. Matches any character except line breaks.
* Star. Match 0 or more of the preceding token.
? Lazy. Makes the preceding quantifier lazy, causing it to match as few characters as possible.
)
\] Escaped character. Matches a "]" character (char code 93).
] Character. Matches a "]" character (char code 93).
Upvotes: 1
Reputation:
var str = 'Hello, my [[name]] is [[Joffrey]]';
var a = str.match(/\[\[(.*?)\]\]/g);
Upvotes: 0
Reputation: 1993
var regex = /\[\[(.*?)\]\]/g;
var input = 'Hello, my my [[name]] is [[Joffrey]]';
var match;
do {
match = regex.exec(input);
if (match) {
console.log(match[1]);
}
} while (match);
Will print both matches in your console. Depending on whether you want to print out even blank values you would want to replace the "*" with a "+" /\[\[(.+?)\]\]/g
.
Upvotes: 2
Reputation: 1400
try this /\[\[(\w+)\]\]/g
Demo in regex101 https://regex101.com/r/xX1pP0/1
Upvotes: 0