Java RegEx匹配器中断BMP之外的字符

时间:2019-05-23 13:17:22

标签: java regex xml supplementary

我目前正在编写一个util类来对 sanitize 输入进行保存,该类已保存到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'
    }

}

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

谢谢!

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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