4

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?

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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(" -"));

1 Comment

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!
0

Couldn't you just do this?

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

Comments

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

Comments

0

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

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.