.net - RegEx 删除除 CR 或 LF 之外的所有控制/不可见字符

标签 .net regex unicode

我正在尝试使用正则表达式 (.Net) 来“清理”Unicode 输入字符串——要求是删除除 CR(回车)和 LF(换行符)之外的所有不可见字符/控制字符。换句话说,保留所有有效的可打印字符(英语和法语),包括 CR 和 LF。

我已经尝试了以下(只是使用下划线来查看被替换的内容),但它也删除了 CR/LF ...

clean_str = Regex.Replace( in_str, "\p{C}+", "_" )

也试过:

clean_str = Regex.Replace( in_str, "(\p{Cf}|\p{Co}|\p{Cs}|\p{Cn}|[\x00-\x09]|\x0b|\x0c|[\x0e-\x1f]|\x7f)+", "_" )

来自 http://www.regular-expressions.info/unicode.html ...

p{C} or \p{Other}: invisible control characters and unused code points.

 ◦\p{Cc} or \p{Control}: an ASCII 0x00–0x1F or Latin-1 0x80–0x9F control character.
 ◦\p{Cf} or \p{Format}: invisible formatting indicator.
 ◦\p{Co} or \p{Private_Use}: any code point reserved for private use.
 ◦\p{Cs} or \p{Surrogate}: one half of a surrogate pair in UTF-16 encoding.
 ◦\p{Cn} or \p{Unassigned}: any code point to which no character has been assigned.

Guru's - 如果您有更好/更有效的方法 - 请发布!

提前致谢!

最佳答案

您可以使用字符类减法从控制字符类中排除 CR 和 LF:

clean_str = Regex.Replace( in_str, "[\p{C}-[\r\n]]+", "" )

关于.net - RegEx 删除除 CR 或 LF 之外的所有控制/不可见字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28352804/

相关文章:

c# - 在控制台应用程序中实例化 WinForm

c# - 使用 GraphicsPath 正确绘制文本

c# - .net 无缝 c# + f#

python - 使用 Django 将 Unicode 子类存储到 MySQL

c# - Silverlight 错误找不到类型或命名空间名称 'MatchTimeoutInMilliseconds'

python - 用于在 Python 中删除字符串中所有 URL 的正则表达式

php - 如何转义正则表达式中的斜杠?

regex - 正则表达式 intellij-idea 替换

unicode - Unicode 是否有定义的最大代码点数?

python - 带有 Unicode 项的 ConfigParser