Search code examples
regexregex-lookarounds

Using Regex to delete contents between repeating brackets


I'm trying to remove unneeded words between brackets that contains certain modifier ('DeleteMe') and don't delete contents between brackets that contains other words ('DontDeleteMe'). I though it was simple but proved difficult due to repeating brackets see below.

[
aljdsfjfldsa      DeleteMe         aldsjflajdf
]
[
aldskjfal         DontDeleteMe     asdlkjflasdj
]
[
aljdsfjfldsa      DeleteMe         aldsjflajdf
]
[
aldskjfal         DontDeleteMe     asdlkjflasdj
]

Desired output

[
aldskjfal         DontDeleteMe     asdlkjflasdj
]
[
aldskjfal         DontDeleteMe     asdlkjflasdj
]

I tried the following but the problem is the second line will be deleted with the third line.

(?s)\[.*?'DeleteMe'.*?\]

Solution

  • You can use a word boundary in combination with a negated character class [^

    \[[^][]*\bDontDeleteMe\b[^][]*\]
    

    Regex demo

    If the word is DeleteMe you can match it using word boundaries and repace with an empty string.

    \[[^][]*\bDeleteMe\b[^][]*\]
    

    Regex demo