Reputation: 439
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
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
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.
^\[\[(((?!\[)(?!\]).)+)\]\]$
You could use group 1 for selecting text only.
Upvotes: 1
Reputation: 4516
This regex should work for you assuming there are no [
or ]
characters between the double brackets.
(?<=\[\[)([^\[\]]*)(?=\]\])
Upvotes: 0