Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a string between characters in javascript regex

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

like image 581
heydon Avatar asked Jul 27 '26 10:07

heydon


2 Answers

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.

like image 178
jvecsei Avatar answered Jul 30 '26 00:07

jvecsei


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).
like image 34
Husein Avatar answered Jul 29 '26 22:07

Husein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!