Search code examples
javascriptregexbrackets

Regex to get the word after brackets


I would like to have a Regex select the next word after brackets containing letters. There can be more than multiple brackets following each other before the next word.

Example:

[X]word[y][Z]another Expected output: word, another

I would like also to achieve the same but providing the regex the content between the brackets and get the following word:

Example 2: i would like the next word after [y]:

[X]word[y][Z]another Expected output: another

I tried (?m)^\[[^\]\[]*\]\K.+ but somehow it's not working.


Solution

  • Javascript does not support \K or inline modifiers like (?m)

    You might use for example a capture group for 1 or more word characters, and first match from [...]

    \[[^\][]*](\w+)
    

    Regex demo

    Or providing the regex the content between the brackets and capture the following word, by optionally repeating [...] after it:

    \[y](?:\[[^\][]*])*(\w+)
    

    Regex demo