1

I want to replace \" characters in a string like \"someword\". But this regex "(\\\")+" doesn't work.

Regex.Replace(string_, "(\\\")+", String.Empty);
2
  • 1
    Is the task to just replace " with empty string? Then you do not need any regex, just s = old_s.Replace("\"", string.Empty);. Commented Oct 7, 2015 at 8:36
  • yes that is finally what i did. And now it works. Commented Oct 7, 2015 at 8:44

2 Answers 2

2

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:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

If your task is just to remove all "s, you do not need any regex, just use s = old_s.Replace("\"", string.Empty);.
1

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.

1 Comment

Note that "(\\\")+" is in fact \"+ regex, and is equal to just "+ as a double quote does not need to be escaped. Is the task to just replace " with empty string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.