从java中的字符串中删除无效的XML字符

从java中的字符串中删除无效的XML字符

问题描述:

Hi
我想从字符串中删除所有无效的XML字符。
i希望使用带有string.replace方法的正则表达式。

Hi i would like to remove all invalid XML characters from a string. i would like to use a regular expression with the string.replace method.

喜欢

line.replace(regExp,);

使用什么样的regExp?

what is the right regExp to use ?

无效的XML字符是不是这样的一切:

invalid XML character is everything that is not this :

[#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

谢谢。

Java的正则表达式支持补充字符,因此您可以使用两个UTF-16编码字符指定这些高范围。

Java's regex supports supplementary characters, so you can specify those high ranges with two UTF-16 encoded chars.

以下是删除 XML 1.0

// XML 1.0
// #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
String xml10pattern = "[^"
                    + "\u0009\r\n"
                    + "\u0020-\uD7FF"
                    + "\uE000-\uFFFD"
                    + "\ud800\udc00-\udbff\udfff"
                    + "]";

大多数人都想要XML 1.0版本。

Most people will want the XML 1.0 version.

以下是在 XML 1.1中删除非法字符的模式

// XML 1.1
// [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
String xml11pattern = "[^"
                    + "\u0001-\uD7FF"
                    + "\uE000-\uFFFD"
                    + "\ud800\udc00-\udbff\udfff"
                    + "]+";

您需要使用 String.replaceAll(.. 。) 而不是 String.replace(...)

String illegal = "Hello, World!\0";
String legal = illegal.replaceAll(pattern, "");