简体   繁体   中英

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

The documentation states that this value is:

Return Value

Type: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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