如何从一个字符串剥离非字母数字字符(包括空格)? [英] How do I strip non-alphanumeric characters (including spaces) from a string?

查看:88
本文介绍了如何从一个字符串剥离非字母数字字符(包括空格)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何剥离从字符串非字母数字字符和空格松在C#替换为?

How do I strip non alphanumeric characters from a string and loose spaces in C# with Replace?

我要保持A-Z,A-Z,0-9,仅此而已(甚至不是,空格)。

I want to keep a-z, A-Z, 0-9 and nothing more (not even " " spaces).

"Hello there(hello#)".Replace(regex-i-want, "");

应该给

"Hellotherehello"

我曾尝试你好(你好#)替换(@[^ A-ZA-Z0-9],); 但空间依然存在。

推荐答案

在您的正则表达式,你已经被排除匹配的空间(和你没有使用 Regex.Replace()我已经完全忽略...):

In your regex, you have excluded the spaces from being matched (and you haven't used Regex.Replace() which I had overlooked completely...):

result = Regex.Replace("Hello there(hello#)", @"[^A-Za-z0-9]+", "");

应该工作。在 + 使得正则表达式多一点效率由一个一次而不是一个匹配多个连续的非字母数字字符。

should work. The + makes the regex a bit more efficient by matching more than one consecutive non-alphanumeric character at once instead of one by one.

如果您想保留非ASCII字母/数字,也请使用以下正则表达式:

If you want to keep non-ASCII letters/digits, too, use the following regex:

@"[^\p{L}\p{N}]+"

这让

BonjourmesélèvesGutenMorgenliebeSchüler

而不是

BonjourmeslvesGutenMorgenliebeSchler

这篇关于如何从一个字符串剥离非字母数字字符(包括空格)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆