Home > OS >  Use Regex to replace dashes and keep hyphens?
Use Regex to replace dashes and keep hyphens?

Time:03-14

I want to replace dashes with a full-stop (.). If the dash appears as a hyphen it should be ignored. E.g. -ac-ac with .ac-ac

I started with the following regex: (?<!\s|\-)\- |\- (?!\s|\-)

CodePudding user response:

You can use

\B-|-\B

See the regex demo.

The pattern matches

  • \B- - a hyphen that is preceded by a non-word char or is at the start of a string
  • | - or
  • -\B - a hyphen that is followed by a non-word char or is at the end of a string.

See the Python demo:

import re
text = "-ac-ac"
print( re.sub(r'\B-|-\B', '.', text) )
# => .ac-ac

If you want to only narrow this down to letter context, replace \B with negative lookarounds containing a letter pattern:

(?<![^\W\d_])-|-(?![^\W\d_])

See this regex and Python demo.

  • Related