为什么 String.split 需要管道分隔符才能转义? [英] Why does String.split need pipe delimiter to be escaped?

查看:20
本文介绍了为什么 String.split 需要管道分隔符才能转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析一个文件,该文件的每一行都带有管道分隔值.当我没有在 split 方法中转义管道分隔符时,它无法正常工作,但在我转义管道后它正常工作,如下所示.

I am trying to parse a file that has each line with pipe delimited values. It did not work correctly when I did not escape the pipe delimiter in split method, but it worked correctly after I escaped the pipe as below.

private ArrayList<String> parseLine(String line) {
    ArrayList<String> list = new ArrayList<String>();
    String[] list_str = line.split("\|"); // note the escape "\" here
    System.out.println(list_str.length);
    System.out.println(line);
    for(String s:list_str) {
        list.add(s);
        System.out.print(s+ "|");
    }
    return list;
}

有人可以解释为什么需要为 split() 方法转义管道字符吗?

Can someone please explain why the pipe character needs to be escaped for the split() method?

推荐答案

String.split 需要一个正则表达式参数.未转义的 | 被解析为正则表达式,意思是空字符串或空字符串",这不是您的意思.

String.split expects a regular expression argument. An unescaped | is parsed as a regex meaning "empty string or empty string," which isn't what you mean.

这篇关于为什么 String.split 需要管道分隔符才能转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆