我需要用空格+相同的字符替换以下字符,只要它们是字符串的第一个字符:
"-"
"+"
"="
Run Code Online (Sandbox Code Playgroud)
例如.
"+hello" should become " +hello"
"-first-second" should become " -first-second"
Run Code Online (Sandbox Code Playgroud)
用于此任务的非正则表达式方法更合适:
if (s.StartsWith("-") || s.StartsWith("+") || s.StartsWith("="))
s = string.Format(" {0}", s);
Run Code Online (Sandbox Code Playgroud)
或者,如果您想进一步扩展此方法,可以使用正则表达式方法:
var result = Regex.Replace("-hello", @"^([-+=])", " $1");
Run Code Online (Sandbox Code Playgroud)
正则表达式:
^ - 断言字符串开头的位置([-+=])- 匹配并捕获-或+或=符号在替换字符串中,我们使用对捕获文本的反向引用 $1.