英文:
Regex Replace exact matching ( include special character )
问题
output = "John + Daniels";
英文:
I have a string;
string input = "John + Daniels";
I want to replace the word " + Daniels"
with a space.
like this: input = "John";
https://dotnetfiddle.net/bakGp9
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "John + Daniels";
string withSpecialCharacter = string.Concat("\b" + " + Daniels" + "\b");
StringBuilder tempString = new StringBuilder();
tempString.AppendFormat(@"{0}", withSpecialCharacter);
string finalString = tempString.ToString();
string result = Regex.Replace(input, finalString, "");
Console.WriteLine(result);
}
}
but Replace doesn't work.
output = "John + Daniels";
答案1
得分: 1
将您的逐字输入传递给 Regex.Escape
,以便适当地对其进行转义,以在模式中使用。确保对\b
转义序列使用逐字字符串文字(@"..."
):
string pattern = @"\b" + Regex.Escape(" + Daniels") + @"\b";
// ...
string result = Regex.Replace(input, pattern, "");
英文:
Pass your verbatim input to Regex.Escape
in order to appropriately escape it for use in a pattern. Make sure to use verbatim string literals (@"..."
) for the \b
escape sequence:
string pattern = @"\b" + Regex.Escape(" + Daniels") + @"\b";
// ...
string result = Regex.Replace(input, pattern, "");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论