0

I have a string like this:

This is very sad, and this is [very sad] and [test;very sad]

What I need, is a regexp that will capture ‘very sad’ only if it is not inside brackets. I tried something like this:

[^\[](very sad)[^\]]

But it doesn’t seem to work if ‘very sad’ is at the beginning of the string, and when it does – it captures some extra spaces around the string, as can be seen here:

https://regex101.com/r/zwgeXg/1

user2384366
  • 1,034
  • 2
  • 12
  • 28
  • 1
    A usual workaround is `very sad(?![^\][]*])` – Wiktor Stribiżew May 01 '18 at 17:11
  • 2
    @WiktorStribiżew or `very sad(?![^[]*])` – Roko C. Buljan May 01 '18 at 17:16
  • 1
    @RokoC.Buljan Yes, anyway, I cannot find the exact duplicate. A solution is just to match anything inside square brackets and then match what OP needs in other contexts. `/\[[^\][]*]|(very sad)/g`, and then use some code to apply the necessary changes. – Wiktor Stribiżew May 01 '18 at 17:19
  • 1
    or see [Regex for matching a character, but not when it's enclosed in square bracket](https://stackoverflow.com/questions/12204657/regex-for-matching-a-character-but-not-when-its-enclosed-in-square-bracket) – revo May 01 '18 at 17:34
  • @WiktorStribiżew Thanks, your answer as well as RokoC.Buljan answer seem to work but if don’t mind me asking - are they equivalent? Looking at the regexp101, I can’t seem to understand the difference… – user2384366 May 01 '18 at 17:50
  • 1
    They are not equivalent. But will work for this concrete case. – Wiktor Stribiżew May 01 '18 at 18:05

0 Answers0