views:

835

answers:

6

if i have a string like this "Hello - World - Hello World"

I want to replace the characters PRECEDING the FIRST instance of the substring " - "

e.g. so replacing the above with "SUPERDOOPER" would leave: "SUPERDOOPER - World - Hello World"

So far I got this: "^[^-]* - "

But this INCLUDES the " - " which is wrong.

how to do this with regex please?

+3  A: 

Use a non-capturing group, which looks ahead of the pattern to verify the match, but does not include those characters in the match itself.

(^[^-]*)(?: -)

Edit: after thinking about it again, that seems a little redundant. Wouldn't this work?:

^[^-]*

Gets all non-dash characters between the beginning of the string and continues until it hits a dash? Or do you need to exclude the space as well? If so, go with the first one.

Rex M
Non-capturing group will not create group, but will include that its part into the whole match (group #0). So, your first example won't work.
Rorick
A: 

Couldn't you just do this?

Regex.Replace("World - Hello World", "^[^-]* -", "SUPERDOOPER -");

A: 
Regex.Replace(input, @"(Hello)( -.*\1)", @"SUPERDOOPER$2");
Juliet
A: 

The pattern: ([^-]+) (- .+)

First expression matches any series of chars not including a dash. Then there's a space. Second expression starts with a dash and a space, followed by a series of one or more "any" chars.

The replacement: "Superdooper $2"

delivers Superdooper - World - Hello World

Cheeso
A: 

You can try using regex with positive lookahead: "^[^-]*(?= - )". As far as I know C# supports it. This regex will match exactly what you want. You can find out more about lookahead, look-behind and other advanced regex techniques in famous book "Mastering Regular Expressions".

Rorick
A: 

Why do you think that you need to use a regular expression for a string operation like this?

This is simpler and more efficent:

str = "SUPERDOOPER" + str.Substring(str.IndexOf(" -"));
Guffa
thanks Guffa, this is the solution i went with. Thanks to everybody else for their replies too. I learned a lot from this post. Cheers!