.net – C# Regex Replace Question – Education Career Blog

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?

,

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.

,

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

,

Couldn’t you just do this?

Regex.Replace(“World – Hello World”, “^^-* -“, “SUPERDOOPER -“);

,

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

,

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

,

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

Leave a Comment