简体   繁体   中英

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 - ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM