Saif Khan
Saif Khan

Reputation: 18772

Remove square brackets and single quotes regex not working

I have the following string

[custID] = 'A99999999'

I am trying the following to remove the square brackets and the single quotes

Regex.Replace(sql, "/[\[\]']+/g", " ")

but that's not working. I keep getting the same results

Note: sql is a variable holding the string above.

I want the result to be

custID = A99999999

Upvotes: 5

Views: 12931

Answers (5)

manojlds
manojlds

Reputation: 301037

You can use string split and join like below:

        string sql = "[custID] = 'A99999999'";
        var correctedString = string.Join("",sql.Split(new char[] {'[', ']', '\''}));
        Console.Write(correctedString);

If you want to use regex use [\[\]'] to replace those.

Upvotes: 0

svick
svick

Reputation: 244757

You can use this:

Regex.Replace(sql, "[][']", "")

If you're wondering how does that work, ] right after [ isn't treated as closing, but as literal character.

Upvotes: 1

entonio
entonio

Reputation: 2173

I think you're looking for Regex.Replace(sql, @"[\[\]']", " "); the @ introduces a string where you need no escapes, and Regex.Replace replaces all matches, so no need for the g flag - your regex syntax isn't supported here, I think.

Upvotes: 1

Blindy
Blindy

Reputation: 67352

\[ doesn't do what you think it does. Nor is Regex the same as in Perl. Try this instead:

Regex.Replace(sql, @"[\[\]']+", "");

Upvotes: 14

AllenG
AllenG

Reputation: 8190

Is this what you're looking for? ['\\/]

That should match any single character that is a slash or single quote.

Upvotes: 2

Related Questions