zkwsk
zkwsk

Reputation: 2136

Regex select between brackets if given word is found

I need to work out a regex that can select text surrounded by square brackets given that a particular word is present between the brackets.

I've gotten pretty close with this rule:

/\[(.*?)ermittelbar(.*?)\]/gi

(the word I'm currently targeting is "ermittelbar")

Problem is, if I test it on regexr.com for example I see that if I place any opening brackets before the text I wish to match, the selection is extended to include that opening bracket and anything in between.

So:

[created ermittelbar]

Is matched. But so is:

[ ]was [created ermittelbar]

Closing or opening brackets after my initial selection are not included unless the target word is included.

Any ideas how I can fix this?

Upvotes: 4

Views: 615

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

Instead of .* pattern use [^\][] to match any char excluding brackets:

/\[([^\][]*?)ermittelbar([^\][]*)\]/gi

See the regex demo.

Details

  • \[ - [ char
  • ([^\][]*?) - Group 1: any char other than [ and ], as few as possible
  • ermittelbar - a literal substring
  • ([^\][]*) - Group 2: any char other than [ and ], as many as possible
  • \] - ] char.

Upvotes: 2

Related Questions