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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With