Regex find instance of dash, but not dash

后端 未结 3 1434
南笙
南笙 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: -(?<!\s-(?!=\s))
    Replace With: (a space)

    The pattern matches:

    • - - a hyphen
    • (?<!\s-(?!=\s)) - 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).

    0 讨论(0)
  • 2021-01-18 13:50

    Use \w(-)\w to replace all hyphens surrounded by alphabetic characters, digits and underscores, or [^ ](-)[^ ] to replace all hyphens surrounded by non-space characters.

    Both work fine in my Notepad++ version with all of your examples.

    0 讨论(0)
  • 2021-01-18 13:51

    To ignore dashes already with a pre/post space you could use positive lookarounds to assert that what is on the left and on the right are a non whitespace character \S

    In the replacement use a space.

    (?<=\S)-(?=\S)

    Regex demo

    0 讨论(0)
提交回复
热议问题