To match any text in between two adjacent open and close square brackets, you can use the following pattern:
\[([^\][]*)]
(?<=\[)[^\][]*(?=])
See the regex demo #1 and regex demo #2. NOTE: The second regex with lookarounds is supported in JavaScript environments that are ECMAScript 2018 compliant. In case older environments need to be supported, use the first regex with a capturing group.
Details:
(?<=\[)
- a positive lookbehind that matches a location that is immediately preceded with a [
char (i.e. this requires a [
char to occur immediately to the left of the current position)
[^\][]*
- zero or more (*
) chars other than [
and ]
(note that ([^\][]*)
version is the same pattern captured into a capturing group with ID 1)
(?=])
- a positive lookahead that matches a location that is immediately followed with a ]
char (i.e. this requires a ]
char to occur immediately to the right of the current regex index location).
Now, in code, you can use the following:
const text = "[Some text] ][with[ [some important info]";
console.log( text.match(/(?<=\[)[^\][]*(?=])/g) );
console.log( Array.from(text.matchAll(/\[([^\][]*)]/g), x => x[1]) );
// Both return ["Some text", "some important info"]
Here is a legacy way to extract captured substrings using RegExp#exec
in a loop:
var text = "[Some text] ][with[ [some important info]";
var regex = /\[([^\][]*)]/g;
var results=[], m;
while ( m = regex.exec(text) ) {
results.push(m[1]);
}
console.log( results );