Name: John
Surname: Doe
Age: 24
When I do
Regex.Replace(str,"(?<=^|\n)(.*)(?=:)", "")
I get
: John
: Doe
: 24
I want to get rid of the colons without using another replace
The (?=:)
is a positive lookahead that is a non-consuming pattern. The :
char is tested but it does not land inside the match value, and is thus not replaced with the Regex.Replace
method.
You may make your pattern work by mere converting the lookahead pattern into a consuming pattern, i.e. (?=:)
=> :
, but you may simplify your pattern using
(?m)^.*:
See the regex demo
The (?m)^
matches the start of a line, there is no need using (?<=^|\n)
as it denotes exactly that. Then, .*:
matches any 0+ chars other than a newline as many as possible up to the last :
and also that last :
.
To also remove the whitespace after :
, you may add \s*
, or (if you want to only handle horizontal whitespace chars) [\p{Zs}\t]*
.