简体   繁体   中英

C#: Replace Certain Characters if they are the First Character of the String Using Regex

I need to replace the following characters with space + same character only if they are the first character of the string:

"-"
"+"
"="

Non-regex approach for this task is more appropriate:

if (s.StartsWith("-") || s.StartsWith("+") || s.StartsWith("="))
     s = string.Format(" {0}", s);

Or a regex approach can be used if you want to further expand this:

var result = Regex.Replace("-hello", @"^([-+=])", " $1");

The regex:

  • ^ - Assert the position at the beginning of the string
  • ([-+=]) - match and capture the - or + or = symbol

In the replacement string, we are using a back-reference $1 to the captured text.

See a regex demo here .

Regex rgx = new Regex("^[-+=]");
string text = "+x" //your Text goes here
if (rgx.IsMatch(text))
{
    text = " " + text;
}

Another way

var startChars = new List<string> { "+", "-", "=" };
if(startChars.Contains(text.First())
{
   text = $" {text.Substring(1,text.Length-1)}";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM