Reputation: 269
I have the following:
this.LocationCode = this.LocationCode.Replace(@"""", String.Empty);
However I would like to use regex instead. I've used the next block of code but it doesn't do anything to the string. (They are in seperate classes but I've put them all together here for convenience)
public const string checkStringForDoubleQuotes = @"^[""]$";
Regex doubleQuotesPattern = new Regex(RegexChecks.checkStringForDoubleQuotes);
this.LocationCode = Regex.Replace(this.LocationCode, doubleQuotesPattern.ToString(), "");
Can anyone see where I'm going wrong? When LocationCode comes through it contains "K\"23". When I use the string replace it produces "K23" which is perfect, but the Regex way just leaves the value as it is.
SOLUTION
After tinkering around a little more I now have the following:
public const string checkStringForDoubleQuotes = @"["" ,]";
Regex doubleQuotesPattern = new Regex(RegexChecks.checkStringForDoubleQuotes )
this.LocationCode = doubleQuotesPattern.Replace(this.LocationCode, "");
This has allowed me to add more criteria (the comma ,) into the regex string which I wanted the option to do but realised I hadn't added that part in my question, sorry! This way is acceptable for the project, so thanks to all who helped out.
Upvotes: 0
Views: 12795
Reputation: 167
Use this:
s = s.Replace("\"", string.Empty);
OR
s = s.Replace(@"""", string.Empty);
Upvotes: 1
Reputation: 43083
The regex ^["]$
tries to match a string containing one single quote.
"K\"23"
won't match because the double quote is not alone. Basically, the regex will only match this string: """"
and nothing else.
The Replace
solution is here the most straight forward solution.
A regex only solution would be:
public const string checkStringForDoubleQuotes = @"""";
this.LocationCode = Regex.Replace(this.LocationCode, checkStringForDoubleQuotes, string.Empty);
Upvotes: 4