简体   繁体   English

regex.replace不替换任何东西

[英]regex.replace not replacing anything

我想用\\" \\"someword\\"这样的字符串替换\\"字符。但是此正则表达式"(\\\\\\")+"不起作用。

Regex.Replace(string_, "(\\\")+", String.Empty);

Non-escaped quote removal 不转义的报价删除

If your task is just to remove all non-escaped double quotes, you do not need any regex, just use 如果您的任务只是删除所有非转义的双引号,则不需要任何正则表达式,只需使用

s = old_s.Replace("\"", string.Empty);

Literally-escaped quotes 文字转义的引号

In case you can have more than just a double quote escaped in your input, you'd need a more robust solution that will keep all other escaped symbols intact. 如果您在输入中不仅可以使用双引号转义,则需要一种更可靠的解决方案,该方案将使所有其他转义符号保持完整。 It is possible to do with a match evaluator: 可以使用匹配评估程序:

var old_text= @"\\""someword\"""; // Literal \\"someword\", escaped backslash at the start
var stext = Regex.Replace(old_text, @"\\(.)", 
               m => m.Groups[1].Value == "\"" ? "\"" : m.Groups[1].Value);

Result - only the last " is changed as it is the only literally escaped double quote: 结果-仅更改了最后一个" ,因为它是唯一在字面上转义的双引号:

在此处输入图片说明

Try: 尝试:

var myNewString = Regex.Replace(string_, "(\\\")+", String.Empty);

as you can see from MSDN Regex.Replace documentation this method has a return value of type string MSDN Regex.Replace文档中可以看到,此方法的返回值为string类型

The documentation states that this value is: 文档指出此值为:

Return Value 返回值

Type: System.String 类型:System.String

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 与输入字符串相同的新字符串,只是替换字符串代替每个匹配的字符串。 If pattern is not matched in the current instance, the method returns the current instance unchanged. 如果当前实例中的pattern不匹配,则该方法将不变地返回当前实例。

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

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