用|分割字符串java中的分隔符

时间:2022-03-15 01:41:47

I have a string that's like this: 1|"value"|;

我有一个像这样的字符串:1 |“value”|;

I want to split that string and have chosen | as the separator.

我想拆分那个字符串并选择了|作为分隔符。

My code looks like this:

我的代码如下所示:

String[] separated = line.split("|");

What I get is an array that contains all characters as one entry:

我得到的是一个包含所有字符作为一个条目的数组:

separated[0] = ""
separated[1] = "1"
separated[2] = "|"
separated[3] = """
separated[4] = "v"
separated[5] = "a"
...

Does anyone know why?
Can't I split an string with |?

有谁知道为什么?我不能用|拆分字符串吗?

11 个解决方案

#1


68  

| is treated as an OR in RegEx. So you need to escape it:

|在RegEx中被视为OR。所以你需要逃脱它:

String[] separated = line.split("\\|");

#2


10  

You have to escape the | because it has a special meaning in a regex. Have a look at the split(..) method.

你必须逃避|因为它在正则表达式中具有特殊含义。看看split(..)方法。

String[] sep = line.split("\\|");

The second \ is used to escape the | and the first \ is used to escape the second \ :).

第二个\用于逃避|并且第一个\用于逃避第二个\ :)。

#3


4  

The parameter to split method is a regex, as you can read here. Since | has a special meaning in regular expressions, you need to escape it. The code then looks like this (as others have shown already):

split方法的参数是正则表达式,您可以在这里阅读。自|在正则表达式中有特殊含义,你需要转义它。然后代码看起来像这样(正如其他人已经显示的那样):

String[] separated = line.split("\\|");

#4


3  

Try this: String[] separated = line.split("\\|");

试试这个:String [] separated = line.split(“\\ |”);

My answer is better. I corrected the spelling of "separated" :)

我的回答更好。我纠正了“分开”的拼写:)

Also, the reason this works? | means "OR" in regex. You need to escape it.

这也是有效的原因吗? |在正则表达式中表示“OR”。你需要逃脱它。

#5


3  

Escape the pipe. It works.

逃离管道。有用。

String.split("\\|");

The pipe is a special character in regex meaning OR

管道是正则表达式中的特殊字符OR

#6


3  

It won't work this way, because you have to escape the Pipe | first. The following sample code, found at (http://www.rgagnon.com/javadetails/java-0438.html) shows an example.

它不会以这种方式工作,因为你必须逃避Pipe |第一。以下示例代码(http://www.rgagnon.com/javadetails/java-0438.html)显示了一个示例。

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To";
    // bad
    System.out.println(java.util.Arrays.toString(
        testString.split("|")
    ));
    // output : [, R, e, a, l, |, H, o, w, |, T, o]

    // good
    System.out.println(java.util.Arrays.toString(
      testString.split("\\|")
    ));
    // output : [Real, How, To]
  }
}

#7


2  

String.split() uses regex, so you need to escape the '|' like .split("\\|");

String.split()使用正则表达式,所以你需要转义'|'像.split(“\\ |”);

#8


2  

you can replace the pipe with another character like '#' before spliting, try this

您可以在拆分之前用另一个字符替换管道,例如'#',试试这个

String[] seperated = line.replace('|','#').split("#");

#9


0  

| means OR in regex, you should escape it. What's more, a single '\', you get '\|' means nothing in Java string. So you should also escape the '\' itself, which yields '\|'.

|在正则表达式中表示OR,你应该逃避它。更重要的是,单个“\”,你得到'\ |'在Java字符串中没有任何意义所以你也应该逃避'\'本身,这会产生'\ |'。

Good luck!

#10


0  

public class StringUtil {

  private static final String HT = "\t";
  private static final String CRLF = "\r\n";

  // This class cannot be instantiated
  private StringUtil() {
  }

  /**
   * Split the string into an array of strings using one of the separator in
   * 'sep'.
   * 
   * @param s
   *            the string to tokenize
   * @param sep
   *            a list of separator to use
   * 
   * @return the array of tokens (an array of size 1 with the original string
   *         if no separator found)
   */
  public static String[] split(final String s, final String sep) {
    // convert a String s to an Array, the elements
    // are delimited by sep
    final Vector<Integer> tokenIndex = new Vector<Integer>(10);
    final int len = s.length();
    int i;

    // Find all characters in string matching one of the separators in 'sep'
    for (i = 0; i < len; i++)
      if (sep.indexOf(s.charAt(i)) != -1)
        tokenIndex.addElement(new Integer(i));

    final int size = tokenIndex.size();
    final String[] elements = new String[size + 1];

    // No separators: return the string as the first element
    if (size == 0)
      elements[0] = s;
    else {
      // Init indexes
      int start = 0;
      int end = (tokenIndex.elementAt(0)).intValue();
      // Get the first token
      elements[0] = s.substring(start, end);

      // Get the mid tokens
      for (i = 1; i < size; i++) {
        // update indexes
        start = (tokenIndex.elementAt(i - 1)).intValue() + 1;
        end = (tokenIndex.elementAt(i)).intValue();
        elements[i] = s.substring(start, end);
      }
      // Get last token
      start = (tokenIndex.elementAt(i - 1)).intValue() + 1;
      elements[i] = (start < s.length()) ? s.substring(start) : "";
    }

    return elements;
  }

}

#11


0  

Pattern.compile("|").splitAsStream(String you want to split).collect(Collectors.toList());

#1


68  

| is treated as an OR in RegEx. So you need to escape it:

|在RegEx中被视为OR。所以你需要逃脱它:

String[] separated = line.split("\\|");

#2


10  

You have to escape the | because it has a special meaning in a regex. Have a look at the split(..) method.

你必须逃避|因为它在正则表达式中具有特殊含义。看看split(..)方法。

String[] sep = line.split("\\|");

The second \ is used to escape the | and the first \ is used to escape the second \ :).

第二个\用于逃避|并且第一个\用于逃避第二个\ :)。

#3


4  

The parameter to split method is a regex, as you can read here. Since | has a special meaning in regular expressions, you need to escape it. The code then looks like this (as others have shown already):

split方法的参数是正则表达式,您可以在这里阅读。自|在正则表达式中有特殊含义,你需要转义它。然后代码看起来像这样(正如其他人已经显示的那样):

String[] separated = line.split("\\|");

#4


3  

Try this: String[] separated = line.split("\\|");

试试这个:String [] separated = line.split(“\\ |”);

My answer is better. I corrected the spelling of "separated" :)

我的回答更好。我纠正了“分开”的拼写:)

Also, the reason this works? | means "OR" in regex. You need to escape it.

这也是有效的原因吗? |在正则表达式中表示“OR”。你需要逃脱它。

#5


3  

Escape the pipe. It works.

逃离管道。有用。

String.split("\\|");

The pipe is a special character in regex meaning OR

管道是正则表达式中的特殊字符OR

#6


3  

It won't work this way, because you have to escape the Pipe | first. The following sample code, found at (http://www.rgagnon.com/javadetails/java-0438.html) shows an example.

它不会以这种方式工作,因为你必须逃避Pipe |第一。以下示例代码(http://www.rgagnon.com/javadetails/java-0438.html)显示了一个示例。

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To";
    // bad
    System.out.println(java.util.Arrays.toString(
        testString.split("|")
    ));
    // output : [, R, e, a, l, |, H, o, w, |, T, o]

    // good
    System.out.println(java.util.Arrays.toString(
      testString.split("\\|")
    ));
    // output : [Real, How, To]
  }
}

#7


2  

String.split() uses regex, so you need to escape the '|' like .split("\\|");

String.split()使用正则表达式,所以你需要转义'|'像.split(“\\ |”);

#8


2  

you can replace the pipe with another character like '#' before spliting, try this

您可以在拆分之前用另一个字符替换管道,例如'#',试试这个

String[] seperated = line.replace('|','#').split("#");

#9


0  

| means OR in regex, you should escape it. What's more, a single '\', you get '\|' means nothing in Java string. So you should also escape the '\' itself, which yields '\|'.

|在正则表达式中表示OR,你应该逃避它。更重要的是,单个“\”,你得到'\ |'在Java字符串中没有任何意义所以你也应该逃避'\'本身,这会产生'\ |'。

Good luck!

#10


0  

public class StringUtil {

  private static final String HT = "\t";
  private static final String CRLF = "\r\n";

  // This class cannot be instantiated
  private StringUtil() {
  }

  /**
   * Split the string into an array of strings using one of the separator in
   * 'sep'.
   * 
   * @param s
   *            the string to tokenize
   * @param sep
   *            a list of separator to use
   * 
   * @return the array of tokens (an array of size 1 with the original string
   *         if no separator found)
   */
  public static String[] split(final String s, final String sep) {
    // convert a String s to an Array, the elements
    // are delimited by sep
    final Vector<Integer> tokenIndex = new Vector<Integer>(10);
    final int len = s.length();
    int i;

    // Find all characters in string matching one of the separators in 'sep'
    for (i = 0; i < len; i++)
      if (sep.indexOf(s.charAt(i)) != -1)
        tokenIndex.addElement(new Integer(i));

    final int size = tokenIndex.size();
    final String[] elements = new String[size + 1];

    // No separators: return the string as the first element
    if (size == 0)
      elements[0] = s;
    else {
      // Init indexes
      int start = 0;
      int end = (tokenIndex.elementAt(0)).intValue();
      // Get the first token
      elements[0] = s.substring(start, end);

      // Get the mid tokens
      for (i = 1; i < size; i++) {
        // update indexes
        start = (tokenIndex.elementAt(i - 1)).intValue() + 1;
        end = (tokenIndex.elementAt(i)).intValue();
        elements[i] = s.substring(start, end);
      }
      // Get last token
      start = (tokenIndex.elementAt(i - 1)).intValue() + 1;
      elements[i] = (start < s.length()) ? s.substring(start) : "";
    }

    return elements;
  }

}

#11


0  

Pattern.compile("|").splitAsStream(String you want to split).collect(Collectors.toList());