Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex find instance of dash, but not <space>dash<space>

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 search/replace " - " with "foobarfoo" then search for "-" replacing for " " then converting "foobarfoo" back to " - ", but damnit - I'm trying to learn regex!

Here's my problem:

Adapter - BNC Male to BNC-Female, Right Angle

to

Adapter - BNC Male to BNC Female, Right Angle

(note the disappearing dash in "BNC Female")

The closest I am getting is using this: /(?:[^( )])\-(?:[^( )])/g

but that results with it finding the single letter ahead, the dash, and the single letter following:

Adapter - BNC Male to BNC-Female, Right Angle

WHY is it selecting the pre/post characters? Is this not:

(?:[^( )]) find anything except a space (as a noncapturing group)...

\- ... that follows with a dash ...

(?:[^( )]) ... and is followed by anything except a space(as a noncapturing group)

I get even closer is I replace the first term with (?=[^( )]) but if I change the third term to (?![^( )]) I'm back to where I started - just selecting the dash in between the two spaces. GRRRR.

More samples here at http://regexr.com/444i2

like image 881
user10731127 Avatar asked Dec 01 '18 09:12

user10731127


2 Answers

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

like image 149
The fourth bird Avatar answered Oct 11 '22 15:10

The fourth bird


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.

like image 22
Liinux Avatar answered Oct 11 '22 16:10

Liinux