3

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

heydon
  • 315
  • 3
  • 9

4 Answers4

2
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.

jvecsei
  • 1,936
  • 2
  • 17
  • 24
  • As far as I can see, other answers all return [[name]] and [[Joffrey]], not name and Joffrey. Thank you! Only problem is that three values are returned, the last undefined? – heydon Apr 01 '16 at 06:53
  • i can't reproduce the `undefined` problem. If you're executing this in your browser console there might be a `null` or `undefined` at the end because you don't return a value or something. If you just type `input` for example at the end this is removed and you get the input string. But that's not a problem that should occur in a productive webpage. I hope this solves your problem. – jvecsei Apr 02 '16 at 00:06
1

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).
Husein
  • 177
  • 8
0

try this /\[\[(\w+)\]\]/g

Demo in regex101 https://regex101.com/r/xX1pP0/1

thangngoc89
  • 1,400
  • 11
  • 14
0
var str = 'Hello, my [[name]] is [[Joffrey]]';
var a = str.match(/\[\[(.*?)\]\]/g);