How do i match this string?

Viewed 53

The string I have to parse is

[]123 []456

After [], there can be any kind of characters, not only numbers.

I am trying to get the following matches:

[]123
[]456

I tried

/\[](?!\[])+/g

but only get [] and [].

1 Answers

The \[](?!\[])+ pattern matches [] with \[] and then asserts the position is not followed with [] substring. There is no [] after both [], so they are returned as matches. Note there is no point in quantifying the lookahead, it is only checking if its pattern matches or not and returns true or false, so it is in fact just checked once.

You can use

const s = "[]123[]456";
console.log( s.split(/(?!^)(?=\[])/) );
console.log( s.match(/\[][^]*?(?=\[]|$)/g) );

See the regex demo #1 and regex demo #2.

Split solution

The (?!^)(?=\[]) pattern matches any location between a non-start position ((?!^) means any position but start of string) and a [] substring ((?=\[]) is a positive lookahead that matches a location immediately followed with []).

Match solution

The /\[][^]*?(?=\[]|$)/g regex matches all occurrences of

  • \[] - [] substring
  • [^]*? - any 0 or more chars, as few as possible, up to
  • (?=\[]|$) - either [] or end of string.
Related