0

我目前正在编写一个 util 类来清理输入,并将其保存到 xml 文档中。对我们来说,清理意味着,所有非法字符 ( https://en.wikipedia.org/wiki/Valid_characters_in_XML#XML_1.0 ) 都会从字符串中删除。

我试图通过使用一些正则表达式来做到这一点,它用空字符串替换所有无效字符,但是对于 BMP 之外的 unicode 字符,这似乎以某种方式破坏了编码,让我留下了这些?字符。我使用正则表达式替换的哪种方式似乎也无关紧要 ( String#replaceAll(String, String), Pattern#compile(String), org.apache.commons.lang3.RegExUtil#removeAll(String, String))

这是一个带有测试(在 Spock 中)的示例实现,它显示了问题:XmlStringUtil.java

package com.example.util;

import lombok.NonNull;

import java.util.regex.Pattern;

public class XmlStringUtil {

    private static final Pattern XML_10_PATTERN = Pattern.compile(
        "[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\x{10000}-\\x{10FFFF}]"
    );

    public static String sanitizeXml10(@NonNull String text) {
        return XML_10_PATTERN.matcher(text).replaceAll("");
    }

}

XmlStringUtilSpec.groovy

package com.example.util

import spock.lang.Specification

class XmlStringUtilSpec extends Specification {

    def 'sanitize string values for xml version 1.0'() {
        when: 'a string is sanitized'
            def sanitizedString = XmlStringUtil.sanitizeXml10 inputString

        then: 'the returned sanitized string matches the expected one'
            sanitizedString == expectedSanitizedString

        where:
            inputString                                | expectedSanitizedString
            ''                                         | ''
            '\b'                                       | ''
            '\u0001'                                   | ''
            'Hello World!\0'                           | 'Hello World!'
            'text with emoji \uD83E\uDDD1\uD83C\uDFFB' | 'text with emoji \uD83E\uDDD1\uD83C\uDFFB'
    }

}

我现在有一个解决方案,我从单个代码点重建整个字符串,但这似乎不是正确的解决方案。

提前致谢!

4

2 回答 2

1

没有正则表达式的解决方案可能是过滤的代码点流:

public static String sanitize_xml_10(String input) {
    return input.codePoints()
            .filter(Test::allowedXml10)
            .collect(StringBuilder::new,StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
}

private static boolean allowedXml10(int codepoint) {
    if(0x0009==codepoint) return true;
    if(0x000A==codepoint) return true;
    if(0x000D==codepoint) return true;
    if(0x0020<=codepoint && codepoint<=0xD7FF) return true;
    if(0xE000<=codepoint && codepoint<=0xFFFD) return true;
    if(0x10000<=codepoint && codepoint<=0x10FFFF) return true;
    return false;
}

于 2019-05-23T14:02:43.423 回答
1

经过一些阅读和实验,对正则表达式稍作改动(将 替换\x{..}为代理项\u...\u...工作:

private static final Pattern XML_10_PATTERN = Pattern.compile(
        "[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\uD800\uDC00-\uDBFF\uDFFF]"
    );

查看:

sanitizeXml10("\uD83E\uDDD1\uD83C\uDFFB").codePoints().mapToObj(Integer::toHexString).forEach(System.out::println);

结果是

1f9d1
1f3fb
于 2019-05-24T08:39:21.493 回答