繁体   English   中英

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

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

只有当它们是字符串的第一个字符时,我才需要用空格+相同的字符替换以下字符:

"-"
"+"
"="

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

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

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

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

正则表达式:

  • ^ -在字符串开头声明位置
  • ([-+=]) -匹配并捕获-+=符号

在替换字符串中,我们对捕获的文本使用向后引用 $1

在此处查看正则表达式演示

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

其他方式

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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