SimbaNinja
SimbaNinja

Reputation: 43

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.

Upvotes: 0

Views: 135

Answers (3)

jeekiii
jeekiii

Reputation: 296

This:

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

will capture the next word after the bracket which contains the specified character (here [y] as an example), excluding all brackets and stuff inside of them.

Example:

[X]word[y][i][ee][Z]another

=> group1 = "another"

[X]word[y][i][ee][Z]another[eer]eeee[ee]

=> group1 = "another"

and so on.

When asking these type of questions, I suggest you put as many examples as you can, it helps a lot with figuring out what you mean

if you want to change the input character, you can change "y" to whichever character you need in the regex. It should be possible to do programatically

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520938

Here is one regex approach. We can eagerly try to match a term in [...], and that failing, match a single word. Then, we can filter off the terms matched in square brackets, leaving behind the words we want to match.

var input = "[X]word[y][Z]another";
var matches = input.match(/\[.*?\]|\w+/g)
                   .filter(x => !x.match(/^\[.*\]$/));
console.log(matches);

Upvotes: 1

Related Questions