Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for replacing multiple spaces and dashes with or without spaces

Tags:

regex

I can do this with two separate regex passes, but this is already slow and doing two doesn't help, so I want to be able to do it in one pass.

I want to:

  • replace multiple spaces with one space
  • replace a dash (hyphen) with a space

However, if the dash has a space on either side of it then the dash and any spaces either side to be replaced with just one space.

As an example:

a - b c-d e -f g- h i  - j k -  l m  -  n

must end up like

a b c d e f g h i j k l m n

I have tried things like this:

\s+| - | -|- |-

but that doesn't work:

a  b c d e  f g h i  j k   l m   n
like image 963
Graham Avatar asked Sep 17 '14 11:09

Graham


2 Answers

Use the following regexp to match multiple spaces or dashes;

[\s-]+

Replace with a single space.

like image 71
Taemyr Avatar answered Sep 28 '22 07:09

Taemyr


[\s-]+ with a global 'g' modifier and replace with one single space. See here

like image 37
Steven Xu Avatar answered Sep 28 '22 07:09

Steven Xu