简体   繁体   English

Java.split("|") 不工作

[英]Java .split("|") not working

I just ran into the problem that the split method for strings wouldn't work with character "|"我刚刚遇到了字符串的拆分方法不适用于字符“|”的问题as an argument.作为论据。 It somehow separates each character in the string.它以某种方式分隔字符串中的每个字符。

Code:代码:

String[] res = "12345|6".split("|");
Log.d("split", Arrays.toString(res));

Output: Output:

split﹕ [, 1, 2, 3, 4, 5, |, 6]

Use escape character before |在 | 之前使用转义字符like below:像下面这样:

String[] res = "12345|6".split("\\|");

Similar "escape character logic" is required, when you are dealing/splitting with any of the below special characters (used by Regular Expression):当您处理/拆分以下任何特殊字符(由正则表达式使用)时,需要类似的“转义字符逻辑”:

  • OR sign (|)或符号 (|)
  • question mark (?)问号(?)
  • asterisk (*)星号 (*)
  • plus sign (+)加号 (+)
  • backslash (\\)反斜杠 (\\)
  • period (.)时期 (。)
  • caret (^)插入符号 (^)
  • square brackets ([ and ])方括号([ 和 ])
  • dollar sign ($)美元符号 ($)
  • ampersand (&)与号 (&)

| is a regular expression key character and split() works with regualar expressions.是正则表达式键字符, split()与正则表达式一起使用。 Escape it like this: \\\\|像这样转义它: \\\\|

You can try to escape it like this:你可以尝试像这样逃避它:

String[] res = "12345|6".split("\\|");

Pipe has special meaning in regular expression and it allows regular expression components to be logically ORed.管道在正则表达式中具有特殊意义,它允许对正则表达式组件进行逻辑或运算。 So all you need to escape it using the \\\\所以你只需要使用\\\\来逃避它

If you have split using "||"如果您使用“||”进行拆分then you use :然后你使用:

      yourstring.split(Pattern.quote("||"))

You can try this, simple and easy.你可以试试这个,简单易行。

String[] res = "12345|6".split("[|]"); String[] res = "12345|6".split("[|]");

public static void main(String[] args) {
    String data = "12345|6|7|990";
    String[] arr = data.split("\\|");
    for(int i = 0 ; i< arr.length; i++){
      System.out.println(arr[i]);
    }
  }

O/p : 12345
6
7
990

However, I already found a quick fix for this: use ASCII code as argument ->但是,我已经找到了一个快速解决方法:使用 ASCII 代码作为参数 ->

String[] res = "12345|6".split("\\x7C");
Log.d("split", Arrays.toString(res));

Output:输出:

split﹕ [12345, 6]

Just wanted to share this here so others with same issue can also use this fix.只是想在这里分享这个,所以其他有同样问题的人也可以使用这个修复程序。 :) :)

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

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