简体   繁体   English

java中的字符串拆分不能正常工作,给出错误的结果

[英]string split in java is not working as expected giving wrong result

String text="2|919505485043|2013-08-08 12:57:50|2013-08-08 12:58:04|2013-08-08 12:58:08|ANSWER";

I want to split string using | 我想用|分割字符串 .I have the above string in java.When i used 我在java中有上面的字符串。我用的时候

System.out.println(text.split("|").length);

I am getting the result 82.What might be the wrong here. 我得到了结果82.这可能是错的。

String#split uses a regular expression as it argument. String#split使用正则表达式作为参数。 The pipe character | 管道特征| has special meaning (meaning OR) prevents the String from being split internally at every literal | 有特殊含义(意为OR)防止在每一个字面内部被分割字符串| .

It should be escaped 它应该被逃脱

text.split("\\|").length

otherwise the complete String will be used when determining the length 否则,在确定长度时将使用完整的String

String.split(String) uses regular expressions, and | String.split(String)使用正则表达式和| has a special meaning within regular expressions. 在正则表达式中有特殊含义。

Options: 选项:

  • Escape the | 逃避| manually: text.split("\\\\|") 手动: text.split("\\\\|")
  • Escape the | 逃避| programmatically: text.split(Pattern.quote("|")) 以编程方式: text.split(Pattern.quote("|"))
  • Use Guava 's Splitter class instead, to avoid using regular expressions at all 改为使用GuavaSplitter类,以避免使用正则表达式

Personally I would go for the latter approach - I think it's actually a design flaw that String.split uses regular expressions at all, and it's unclear in calling code. 我个人会采用后一种方法 - 我认为它实际上是一个设计缺陷, String.split根本就使用正则表达式,而且在调用代码时也不清楚。

If you really want to use String.split , I'd definitely use Pattern.quote to make it clear to anyone reading the code why you're escaping it - just using "\\\\|" 如果你真的想使用String.split ,我肯定会使用Pattern.quote让任何阅读代码的人都清楚你为什么要逃避它 - 只需使用"\\\\|" isn't very self-documenting, IMO. IMO并不是非常自我记录的。

你忘记了逃脱角色,

text.split("\\\|");

你应该把\\\\忘了这个。

text.split("\\|")
public class Sstring {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String text="2|919505485043|2013-08-08 12:57:50|2013-08-08 12:58:04 |2013-08-08 12:58:08|ANSWER";
        System.out.println(text.split("\\|").length);
        String str[] = text.split("\\|");

        for(String i:str){
            System.out.println(i);
        }
    }

}

Guava, as usual! 番石榴,像往常一样!

Splitter.on("|").split("your_text")

This returns an Iterable. 这将返回一个Iterable。

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

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