Skip to main content
December 22, 2009
Question

Regular Expression - find double hyphens only

  • December 22, 2009
  • 3 replies
  • 3918 views

I am wondering if there's a way to write a regular expression to find double hyphens and change them to single hyphens.  The catch is that some of the text I'm searching through have multiple hyphens.

Example:

str1 = "Here is my sample text with double -- and I would like to replace this with one hyphen."

str2 = "Here is another sample with multiple hyphens ----- that I do not want to change but leave as is."


Is there a way to change only str1 to a single hyphen and keep str2 as is?

This topic has been closed for replies.

3 replies

December 23, 2009

I figured it out.  The answer is ([A-Za-z0-9]--[A-Za-z0-9])|(\s--\s).

December 22, 2009

You are correct.  I should have been more explict.  Here are some real examples.  I hope this helps.

"MS3367--1--9"            This needs to be changed to "MS3367-1-9"

"AN/ALQ--218"            This needs to be changed to "AN/ALQ-218"

"Dashes (-----) will"       This does not need to be changed.

Inspiring
December 22, 2009

You are correct.  I should have been more explict.  Here are some real examples.  I hope this helps.

Helps what?

Have you tried to write the regex yourself, at least?

--

Adam

Inspiring
December 22, 2009

It sounds to me that it's not "double hyphens" you want to replace, but it's space+hyphen+hyphen+space?  Or not-hyphen+hyphen+hyphen+not-hyphen?

The former does not need a regex.  The second is definitely doable with a regex, yes: give it a go working it out for yourself, and report back with results/problems...

--

Adam