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.

Share:
11,697

Related videos on Youtube

Sourabh
Author by

Sourabh

Updated on September 29, 2022

Comments

  • Sourabh
    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. The TrimStart(":".ToCharArray()) removes the character not replaces it. And Replace(":", " ") 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
      Daniel Gimenez almost 11 years
      This regex will match at the start ^: only