Replace a character only in the start of a string
11,697
You can use this regular expression:
var output = Regex.Replace(input, "^:", " ");
But for something this simple, I'd recommend using conventional string methods:
var output =
(!string.IsNullOrEmpty(input) && input[0] == ':')
? " " + input.Substring(1) : input;
Note: the check for null or empty strings may not be necessary in your case.
Related videos on Youtube
Author by
Sourabh
Updated on September 29, 2022Comments
-
Sourabh over 1 year
I want to replace a character
":"
with a space" "
character only in the beginning of a string, if the":"
character is present in the beginning. TheTrimStart(":".ToCharArray())
removes the character not replaces it. AndReplace(":", " ")
replaces all the occurrences of the character even if they are not in start. What is the solution? Can Regex be used for it? Or any other way? The desired result is::abc -> abc abc -> abc a:bc -> a:bc abc: -> abc:
-
Daniel Gimenez almost 11 yearsThis regex will match at the start
^:
only
-