reizintolo
reizintolo

Reputation: 439

Regular expression double brackets [[text]]

I have this regular expression: (?<=\[\[)(.*?)(?=\]\]) for finding the pattern [[some text inside]], and works, but I found a case where doesn't work: [[[ some text]]].

I'm trying to find a solution, to only finding the pattern with double brackets in both sides like [[]] "exactly".

Upvotes: 1

Views: 4889

Answers (3)

Matt Burland
Matt Burland

Reputation: 45135

I don't think you can make this work with the look-behind (besides, Javascript doesn't support look behinds anyway), but you could try this:

(?:(^|[^\[])\[\[)([^\]]*?)(?:\]\](?:($|[^\]])))

The second capture group will contain the text you want.

This matches,

 (^|[^\[])   start of string or NOT a `[`
 \[\[        two opening brackets
 ([^\]]*?)   any number of non closing brackets `]`
 \]\]        two closing brackets
 ($|[^\]])   End of the string or NOT a `]`

Example:

var reg = /(?:(^|[^\[])\[\[)([^\]]*?)(?:\]\](?:($|[^\]])))/;
var text1 = "[[some text]]"
var text2 = "[[[some other text]]]"

reg.test(text1);     // true
reg.test(text2);     // false

reg.exec(text1)      //["[[some text]]", "", "some text", ""]
reg.exec(text2)      // null

Upvotes: 3

Dhrubajyoti Gogoi
Dhrubajyoti Gogoi

Reputation: 1340

Here it is, for selecting anything in between sets of [ and ] brackets:

((?!\])(?!\[).)+

Demo 1
eg.

var str = "[[[ some text]]]"
var res = str.match(/((?!\])(?!\[).)+/g);
console.log(res)

I think your edits made the question very different. Here is one that has strictly two starting and closing brackets.

^\[\[(((?!\[)(?!\]).)+)\]\]$

Demo 2

You could use group 1 for selecting text only.

Upvotes: 1

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4516

This regex should work for you assuming there are no [ or ] characters between the double brackets.

(?<=\[\[)([^\[\]]*)(?=\]\])

Demo on regex101.com

Upvotes: 0

Related Questions