4

我正在尝试删除要使用 Playfair Cipher 加密的字符串中的所有标点符号和空格。我不明白为什么这条线不起作用。

s = Regex.Replace(s, @"[^\w\s]", string.Empty);
4

4 回答 4

9

The [^\w\s] means remove anything that's not a word or whitespace character.

Try this instead:

s = Regex.Replace(s, @"[^\w]", string.Empty);

You could also use:

s = Regex.Replace(s, @"\W", string.Empty);

Of course that will leave underscores as those are considered word characters. To remove those as well, try this:

s = Regex.Replace(s, @"[\W_]", string.Empty);

Or this:

s = Regex.Replace(s, @"\W|_", string.Empty);
于 2013-04-14T21:06:53.930 回答
4

使用 Linq 代替 Regex 怎么样?

string str = "abc; .d";
var newstr = String.Join("", str.Where(char.IsLetterOrDigit));
于 2013-04-14T21:10:17.463 回答
1

^字符意味着不是。我用[^A-Za-z0-9-]连字符代替所有不是字母数字的东西。

于 2013-04-14T21:09:33.007 回答
0

你最好的选择可能是使用[^A-Za-z]contains \w_0-9猜你不想保留它。

以下正则表达式将删除任何 nota-zA-Z.

s = Regex.Replace(s, @"[^A-Za-z]", string.Empty);
于 2013-04-14T21:13:00.367 回答