0

The following works in vb.net, and basically only allows characters on a standard US Keyboard. Any other character pasted gets deleted. I use the following regular expression code:

"[^A-Za-z0-9\[\{\}\]`~!@#$%\^&*\(\)_\-+=\\/:;'""<>,\.|? ]", "")  

However when I try to use it in C# it won't work, I used '\' as a escape sequence. C# seems a bit different when it comes to escape sequences? Any help would be appreciated.

1
  • 1
    Please show the code you are using, both in VB.NET and in C#. Commented Mar 16, 2011 at 3:13

5 Answers 5

3

Prefix the string with @. That's it. From there you can use the regex string from VB as is (including doubling up on the " character).

// Note: exact same string you're using, only with a @ verbatim prefix.
string regex = @"[^A-Za-z0-9\[\{\}\]`~!@#$%\^&*\(\)_\-+=\\/:;'""<>,\.|? ]";
string crazy = "hĀečlĤlŁoźtƢhǣeǮrȡe";
Console.WriteLine(Regex.Replace(crazy, regex, ""));

Output:

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

Comments

0

Prefix your string with "@" and prefix quotes within the string with "\".

I.e. this string

abc\def"hij

in C# would be encoded as

@"abc\def\"hij"

2 Comments

Using the @ prefix, it should be @"bc\def""hij", \ isn't an escape character.
@Rob is right: in a verbatim string literal you escape a double-quote with another double-quote, not with a backslash.
0

You need to escape your " character. Do this by putting a \ before your " character.

"[^A-Za-z0-9[{}]`~!@#$%\^&*()_-+=\/:;'""<>,.|? ]"

should become

"[^A-Za-z0-9[{}]`~!@#$%\^&*()_-+=\/:;'\"\"<>,.|? ]"

If you use the @prefix before this, it will treat the backslash literally instead of an escape character and you wont get the desired result.

1 Comment

Actually, if he sticks a @ onto the string literal, the regex should work as it is. Specifically, the double-quote is already escaped with another double-quote.
0

Escape your characters:

"[^A-Za-z0-9[{}]`~!@#$%\^&*()_-+=\\/:;'\"<>,.|? ]"

A good tool for regular expression design and testing (free) is: http://www.radsoftware.com.au/regexdesigner/

1 Comment

Your first regex won't work because it contains an unescaped double-quote. You need to escape it with another double-quote ("").
0

You need to escape you regex for use in C#

[^A-Za-z0-9\[\{\}\]`~!@#$%\^&*\(\)_\-+=\\/:;'\"<>,\.|? ]

Try this one!

Comments

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.