Dev3
Dev3

Reputation: 31

Regex.Replace c# Removing reserved characters

End of the day brain overload... I'm trying to strip out some characters that are reserved, and my escapes don't seem to be right.

["word"] needs to be word

This is what I'm attempting to use to strip [, ], " yet it's not working right...

Regex.Replace (s, "[\"\\[\\]]", "");

Upvotes: 0

Views: 98

Answers (2)

Mariano
Mariano

Reputation: 6521

Your regex works just fine.

Make sure you assign the result:

string result = Regex.Replace (s, "[\"\\[\\]]", "");

ideone demo


Do consider, that you're stripping all ", [ and ] from the text. If you want to match the subject in a more strict way, you could use something similar to:

string result = Regex.Replace (s, "\\[\"(.*?)\"\\]", "$1");

ideone demo

The regex matches:

  • \\[\" Literal ["
  • (.*?) Any text, repeated as few times as possible, captured in group 1 (because of the parentheses)
  • \"\\] Literal "]

And replaces the match with:

  • $1 Backreference to the text captured by group 1

Upvotes: 1

w.b
w.b

Reputation: 11238

You can do it this way:

string str = @"[""word""]";

string newStr = Regex.Replace(str, @"[^a-zA-Z_0-9]", "");

Console.WriteLine(newStr); // word

Upvotes: 0

Related Questions