开发者

C# Using Regular Expressions

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 regul开发者_开发知识库ar 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.


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


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"


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.


Escape your characters:

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

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


You need to escape you regex for use in C#

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

Try this one!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜