Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spaces around all hyphens in a string without double-up

Tags:

regex

I'm after a regex that puts spaces around each "-" in a string, eg.

02 jaguar-leopard, tiger-panther 08

would become

02 jaguar - leopard, tiger - panther 08

Note that if the "-" already has spaces around it, no changes are to be made, eg.

02 jaguar - leopard, tiger - panther 08

should not become

02 jaguar  -  leopard, tiger  -  panther 08

The number of hyphens are unknown in advance.

Thanks for any ideas...

Edit: I'm not actually using a language for this. I'm using Ant Renamer (a mass file renaming utility). There are two fields in the renamer GUI, "Expression" and "New name" to provide inputs. This is from the help file as an example:

Swapping artist and title from mp3 file names:

Expression = (.) - (.).mp3

New name = $2 - $1.mp3

and

Extract episode number and title from series video files with episode number as SnnEmm followed by title:

Expression = Code.Quantum.S([0-9]{2})E([0-9]{2}).(.*).FRENCH.XViD.avi

New name = Code Quantum - $1$2 - $3.avi

like image 690
Dave Avatar asked Nov 26 '25 02:11

Dave


2 Answers

Replace _*-_* with _-_ (replace the underscores with spaces before using the pattern).

This way, any existing spaces around the hyphen will be replaced by the newly inserted spaces.

like image 150
n.st Avatar answered Nov 28 '25 17:11

n.st


Search:

(?:(\S)| )-(?:(\S)| )

Replace:

$1 - $2

Note that your tool may use backslashes for back references, it might need \1 - \2 instead.

like image 32
Bohemian Avatar answered Nov 28 '25 16:11

Bohemian