Regex find instance of dash, but not dash

后端 未结 3 1460
南笙
南笙 2021-01-18 13:06

I am sooo close. I am trying code a regex expression for Notepad++ to replace a dash with a space, ignoring dashes already with a pre/post space. I realize I could

3条回答
  •  甜味超标
    2021-01-18 13:44

    The most readable option for Notepad++ is an alternation based regex with a conditional replacement pattern:

    Find What: (\s-\s)|-
    Replace With: (?1$1: )

    The (\s-\s)|- pattern either captures into Group 1 a whitespace, - and a whitespace, or just matches -. If Group 1 matches, its value is pasted back where it was (=this match is skipped), else the - in other contexts is replaced with a space.

    See a demo below:

    Another option is using nested lookarounds:

    Find What: -(?
    Replace With: (a space)

    The pattern matches:

    • - - a hyphen
    • (? - this negative lookbehind fails the match if its pattern matches the following pattern immediately to the left of the current location (that is, right after -):
      • \s - a whitespace
      • - - a hyphen (this is necessary to make sure we get to the same place where the lookbehind was triggered)
      • (?!=\s) - the next char is a whitespace (this is a lookahead, it is not possible to make it a simple \s as we cannot let the lookbehind move its pattern position matching, i.e. we can't let it try \s-\s before and including - (it would result in a true result).

提交回复
热议问题