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

11
  • 1
    \[\[(.*?)\]\] Commented Mar 31, 2016 at 11:34
  • show us the js code that you have used Commented Mar 31, 2016 at 11:34
  • 2
    \[\[([^\]])*\g ==> /pattern/g Commented Mar 31, 2016 at 11:34
  • @Tushar I guess you can add this as an answer Commented Mar 31, 2016 at 11:35
  • OP, \[\[(.+?)\]\] use this. @Tushar yours will match [[]] this with an empty string. isn't it? Commented Mar 31, 2016 at 11:35

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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).

Comments

0

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.