Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Replace Question

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?


1 Answers

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.

like image 186
Rex M Avatar answered Oct 26 '25 12:10

Rex M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!