C # Regex Replace Question

if I have a line like this "Hello - World - Hello World"

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

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

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

But that INCLUDES "-", which is not true.

how to do it with regex?

+3
source share
6 answers

Use the non-capture group that looks in front of the template to check for compliance, but does not include these characters in a match in itself.

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

: , . ?:

^[^-]*

, ? ? , .

+3

, , ?

:

str = "SUPERDOOPER" + str.Substring(str.IndexOf(" -"));
+1

?

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

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

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

, . . , "" .

: "Superdooper $2"

Superdooper - World - Hello World

0

You can try using a regular expression with a positive view: "^[^-]*(?= - )". As far as I know, C # supports it. This regular expression will exactly match your desire. You can learn more about lookahead, look-behind, and other good practices for regular expressions in the famous book Mastering Regular Expressions .

0
source

Source: https://habr.com/ru/post/1705543/


All Articles