C#:如果它们是使用正则表达式的字符串的第一个字符,则替换某些字符

时间:2015-09-18 14:50:15

标签: c# regex

我需要将以下字符替换为空格+相同字符,只要它们是字符串的第一个字符:

"-"
"+"
"="

例如

"+hello" should become " +hello"
"-first-second" should become " -first-second"

2 个答案:

答案 0 :(得分:6)

此任务的非正则表达式方法更合适:

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

如果您想进一步扩展它,可以使用正则表达式方法:

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

正则表达式:

  • ^ - 断言字符串开头的位置
  • ([-+=]) - 匹配并捕获-+=符号

在替换字符串中,我们对捕获的文本使用back-reference $1

查看regex demo here

答案 1 :(得分:1)

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