tags:

views:

57

answers:

3

How can i replace Hypen's inside a string, but ignore hypens preceded by a slash eg: "Just-Testing-A-String-\--But i want to leave this hypen"

+1  A: 

Try something like this:

regex ([^\\])-

replace with $1YOURSTRING

lampej
Missed one '\'?
Max
It was the SO editor trying to fix it for me :) Thanks
lampej
FYI - A reference for this method of "negative look-behind" is http://www.regular-expressions.info/lookaround.html
Reddog
+3  A: 

If you want to keep only one hyphen that follows the \, then you can use regex

(?<!\\)-

UPDATE: Actually I don't believe that it is possible to create such a rexeg, because in this case you would have to do two replacements: one is for

'-' to ' ' 

and another one is for

'\-' to '-', 

so you need to run two replacements. The only thing I can think of is if you OK with replacing '\' with ' ' also. Then you can use the following regex

((?<!\\)-)|(\\(?=-))
Max
That leaves `\-` in the output. I believe the author wants `-` left where `\-` was.
Aren
Thats correct. Its bacically a string and i need to replace hypens with spaces, but sometimes may need to have a hypen in hence the \-
Damon
I see. That would be more complicated. Maybe it's easier to run two different replaces one by one. First is the one I indicated and the next one is to remove \
Max
Think thats the way to go. Thank you
Damon
I have updated my answer
Max
And that will do it accompanied by a replace for double spaces
Damon
But that would only work if you run replaces one by one. You cannot run them in one regex, because at the time the search is done there would be no double spaces. This would'n work "((?<!\\)-)|(\\(?=-))|( )"
Max
A: 

What language are you using? I would go about this in different ways depending on the language being used.

The backslash in your example is actually creating an invalid escape character, "-" will throw an error in most languages. Could you mean a foreword slash, "/"?

CMikeB1
Lanugage in use is C#
Damon