Home > database >  Exclude markdown from regex match
Exclude markdown from regex match

Time:09-16

RegEx is not a hobbyhorse of mine, which is why I regularly struggle with it. So far, I have always found a solution myself, but this is where I fail:

I want matching all "\-" except inside square brackets and brackets following square brackets.

\- match \- all \-
[\- match \- none \-]
[\- match \- none \-](\- match \- none \-)
(\- match \- all \-)

After hours of searching and trying around with uncounted variations of "lookaheads" and "lookbehinds" I am unable to achieve the wanted result.

My best attempt but with unexpected result is

\\\-(?!(([^\[]*])|(?!\]\()*?\)))

I have no idea how to exclude "](…)" without excluding "(…)", too. All attempts around that lead to the effect, inexplicable to me, that depending on the position, instead of none, some hits occur.

See: https://regexr.com/6u1v0

Maybe my approach is completely wrong, and I got stuck in it. Either way, I would appreciate a tip.

The "\-" is only one as a sample from a set of meta signs I want to modify.

CodePudding user response:

There is no tool or programming language tagged, but if you want to modify the the matches for \- outside of the brackets, you can use a capture group to keep what you don't want to change, and then using an alternation | match the ones that you want to change.

Then using a programming language for example, you can check if there is a capture group 1 value. If there is, use that in the replacement.

Else use your own replacement value.

(\[[^][]*](?:\([^()]*\))?)|\\-

Explanation

  • ( Capture group 1
    • \[[^][]*] Match from [...]
    • (?:\([^()]*\))? Optionally match (...)
  • ) Close group 1
  • | Or
  • \\- Match \-

See a regex demo.

  • Related