正则表达式替换精确匹配(包括特殊字符)

huangapple go评论61阅读模式
英文:

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, "");

huangapple
  • 本文由 发表于 2023年6月12日 22:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定