Search code examples
regexsublimetext3regex-lookarounds

Regex to replace character between square brackets, but not between parenthesis


I have a list of Markdown links that look like this:

[filename-with-some-words](/001-folder/filename-with-some-words.md)
[title-with-other-words](/001-folder/title-with-other-words.md)
[other-words](/001-folder/other-words.md)

I want to replace the - that occur between square brackets [], but not those that occur between parenthesis () such that my final result would look like:

[filename with some words](/001-folder/filename-with-some-words.md)
[title with other words](/001-folder/title-with-other-words.md)
[other words](/001-folder/other-words.md)

I can match all text between brackets with (?<=\[).+?(?=\]), but how do I match only the dash -?


Solution

  • You may use

    (?:\G(?!\A)|\[)[^][-]*\K-(?=[^][]*])
    

    Replace with a space. See the regex demo.

    Details

    • (?:\G(?!\A)|\[) - either the end of the previous successful match or [
    • [^][-]* - any 0+ chars other than ], [ and -
    • \K - match reset operator discarding all text matched so far from the whole match memory buffer
    • - - a hyphen
    • (?=[^][]*]) - that is followed with 0+ non-bracket chars till a ] char.