繁体   English   中英

Java代码无法识别ctrl-m(^ M),但适用于其他ctrl-characters(^ Q,^ A,^ T等)Linux

[英]Java code does not recognize ctrl-m(^M) but works fine for other ctrl-characters(^Q,^A,^T etc) Linux

我有一个要求,我需要删除两个特定的控制字符: ^@^M ,来自Linux上的Java传入数据。

下面提到的部分按预期工作:

String s;
s = s.replaceAll("\\x00","as");
s = s.replaceAll("\\000", "as");

但这些不是:

s = s.replaceAll("\\015", "as"); //Octal
s = s.replaceAll("\\x0D", "as"); //Hex

我已经尝试了所有可用的表示(八进制/十六进制/ unicode),包括\\r在我的代码中表示^M但它不起作用。 如上所述,一切都适用于其他控制字符。

请建议是否有任何我没有尝试或错过的东西。

编辑:按要求提供可实现的代码。

public class sampSC {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("./samp1.txt"));

        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }

            String s = sb.toString();
            System.out.println(s);
            s = s.replaceAll("\\00", "sb"); //works
            System.out.println(s);
            s = s.replaceAll("\\x11", "s23b"); //works
            System.out.println(s);
            s = s.replaceAll("\\r$", "aa"); //doesn't work
            System.out.println(s);
        } finally {
            br.close();
        }
    }
}

总结注释:使用BufferedReader.readLine()逐行读取文件。 readline剥离换行符^ M(\\ r),因此它永远不会进入稍后搜索的String

如何通过char而不是逐行读取char? 那么替补看起来微不足道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM