C#中正则表达式替换Regex.Replace如何将特殊字符当成普通字符处理

ltolll 2014-04-12 02:58:32
newName = Regex.Replace(newName,pattern, txtReplaceNew, RegexOptions.IgnoreCase);
这里pattern是由用户输入的,可能含有任意字符,包括正则表达式中的特殊字符,而我只想让它在Regex.Replace语句中以普通字符的形态进行匹配newName。需要如何处理?

例:
newName=“[www.cntingshu.com]百家讲坛_春秋五霸03_管仲相齐-李山.20110813”;
pattern=“[www.cntingshu.com]百家讲坛_”;

这里[].都是特殊字符,当然还有其它很多特殊字符。我无法知道用户要输入哪些字符,所以不可能手工加“/”来处理
...全文
1617 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ltolll 2014-04-14
  • 打赏
  • 举报
回复
#3,#8都是有效的,谢谢。
dalmeeme 2014-04-13
  • 打赏
  • 举报
回复 1
正则中有个Escape方法,直接可以将正则表达式中的转义字符当成普通字符匹配:
		string s = @"[www.\cntingshu.com]百家讲坛_";
		string pattern = s;
		bool result = Regex.IsMatch(s, Regex.Escape(pattern));
		Response.Write(result);
//true
本拉灯 2014-04-13
  • 打赏
  • 举报
回复



		public static string StringToPattern(string Str)
		{
			if(Str=="")
				return "";
			
			string[] c={"\\", "^", "$", "{", "[", ".", "(", "*", "+", "?", "!", "#", "|",")"};
			for(int i=0;i<c.Length;i++)
			{
				Str=Str.Replace(c[i],"\\"+c[i]);
			}
			return Str;
		}

devmiao 2014-04-13
  • 打赏
  • 举报
回复
引用 4 楼 ltolll 的回复:
[quote=引用 3 楼 hjywyj 的回复:] pattern=“[www.cntingshu.com]百家讲坛_”; pattern=Regex.Replace(pattern,@"\[|\]|\.",@"\$0");
有效,能否讲一下"\$0"是什么意思?[/quote] 这个是命名分组的意思 自己google下“正则表达式30分钟教程”
zylsky 2014-04-13
  • 打赏
  • 举报
回复
引用 4 楼 ltolll 的回复:
[quote=引用 3 楼 hjywyj 的回复:] pattern=“[www.cntingshu.com]百家讲坛_”; pattern=Regex.Replace(pattern,@"\[|\]|\.",@"\$0");
有效,能否讲一下"\$0"是什么意思?[/quote] 同求
ltolll 2014-04-13
  • 打赏
  • 举报
回复
引用 3 楼 hjywyj 的回复:
pattern=“[www.cntingshu.com]百家讲坛_”; pattern=Regex.Replace(pattern,@"\[|\]|\.",@"\$0");
有效,能否讲一下"\$0"是什么意思?
zylsky 2014-04-13
  • 打赏
  • 举报
回复
引用 6 楼 devmiao 的回复:
[quote=引用 4 楼 ltolll 的回复:] [quote=引用 3 楼 hjywyj 的回复:] pattern=“[www.cntingshu.com]百家讲坛_”; pattern=Regex.Replace(pattern,@"\[|\]|\.",@"\$0");
有效,能否讲一下"\$0"是什么意思?[/quote] 这个是命名分组的意思 自己google下“正则表达式30分钟教程”[/quote] 3q
  • 打赏
  • 举报
回复
pattern=“[www.cntingshu.com]百家讲坛_”; pattern=Regex.Replace(pattern,@"\[|\]|\.",@"\$0");
欢乐的小猪 2014-04-12
  • 打赏
  • 举报
回复
pattern=textbox.text; 直接这样,貌似没什么问题
黄大仙儿 2014-04-12
  • 打赏
  • 举报
回复
“”前面加个@

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧