Lyu JH
Lyu JH

Reputation: 131

Replace hyphen with a dash

Replace every . (dot) with a - (hyphen) except when the dot is surrounded by digits. E.g.: .a.b.1.2. should become -a-b-1.2-

I tried the code

/(^\.|\.$|\b\.\b)(?!\d\.\B)/gm

Substitute

-

Result returned

Test 8/11: Read the task description again. Do not touch anything sandwiched between digits!

How do I modify the Regex?

Regex demo

Upvotes: 2

Views: 169

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use this

(?<!\d|\.)\.+|\.+(?!\d|\.)
  • (?<!\d|\.) - Negative lookbehind. to check preceding character is not digit
  • \. - Matches .
  • (?!\d|\.) - Negative look ahead to check following character is not digit

Demo

Upvotes: 0

Sweeper
Sweeper

Reputation: 270980

Try this regex:

(?<=\D|^)\.|\.(?=\D|$)

and replace with -.

Explanation:

There are only 4 cases where you want to match a dot:

  • there is a non digit before the dot
  • the dot is the start of the string
  • there is a non digit after the dot
  • the dot is the end of the string

The regex just finds all four cases.

Demo

As revo has suggested in the comments, this can be simplified to:

(?<!\d)\.|\.(?!\d)

If lookbehind are not supported by your regex engine, you can replace them with groups:

(\D|^)\.|\.(\D|$)

and replace with $1-$2.

Upvotes: 2

Related Questions