简体   繁体   中英

How to write this regex?

I'm trying to replace all characters except letters, numbers and some special characters with whitespace. This is the line of code I'm using:

documentText = Regex.Replace(documentText, @"^((?![a-zA-Z0-9%\-\@\$&']).*)$", " ");

It doesn't work. I tested it on a sample text like this:

[]\^|+*(){} ~#%=/<>-!@$&_'",.?;:
this should stay

and it removes everything.

Use the following regex:

[^a-zA-Z0-9%\-@$&']

Using ^ inverts the character class, which is perfect for what you're looking for without using a negative lookahead.

你正在寻找。*这意味着0或者更多的任何角色....这就是为什么它会删除所有东西。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM