正则表达式删除所有不可打印的字符

时间:2013-01-28 15:56:57

标签: java android regex

我希望从字符串中删除所有不可打印的ascii字符,同时保留不可见的字符。我认为这会有效,因为空白,\ n \ r是不可见的字符,但不是不可打印的? 基本上我得到一个带有 字符的字节数组,我不希望它们在其中。所以我试图将它转换为字符串,删除 字符再次使用它作为字节数组。

现在我的代码中的空间工作正常,但是现在\ r和\ n不起作用。保留这些也是正确的正则表达式是什么?还是有更好的方式来做我正在做的事情?

public void write(byte[] bytes, int offset, int count) {

    try {
        String str = new String(bytes, "ASCII");
        str2 = str.replaceAll("[^\\p{Print}\\t\\n]", "");
        GraphicsTerminalActivity.sendOverSerial(str2.getBytes("ASCII"));

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }

     return;
 }

} 
编辑:我尝试了[^ \ x00- \ x7F]这是ascii字符的范围....但是 符号仍然通过,很奇怪。

2 个答案:

答案 0 :(得分:10)

以下正则表达式仅匹配可打印文本

[^\x00\x08\x0B\x0C\x0E-\x1F]*

以下Regex会找到不可打印的字符

[\x00\x08\x0B\x0C\x0E-\x1F]

Jave代码:

boolean foundMatch = false;
try {
    Pattern regex = Pattern.compile("[\\x00\\x08\\x0B\\x0C\\x0E-\\x1F]");
    Matcher regexMatcher = regex.matcher(subjectString);
    foundMatch = regexMatcher.find();
    //Relace the found text with whatever you want
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

答案 1 :(得分:1)

在这里,我更喜欢更简单的解决方案。顺便说一句,你忽略了偏移和计数。下面的解决方案会覆盖原始数组。

public void write(byte[] bytes, int offset, int count) {
    int writtenI = offset;
    for (int readI = offset; readI < offset + count; ++readI) {
        byte b = bytes[readI];
        if (32 <= b && b < 127) {
            // ASCII printable:
            bytes[writtenI] = bytes[readI]; // writtenI <= readI
            ++writtenI;
        }
    }
    byte[] bytes2 = new byte[writtenI - offset];
    System.arraycopy(bytes, offset, bytes2, 0, writtenI - offset);
    //String str = new String(bytes, offset, writtenI - offset, "ASCII");
    //bytes2 = str.getBytes("ASCII");
    GraphicsTerminalActivity.sendOverSerial(bytes2);
}