import java.util.Arrays;public class StringDemo {
public static void main(String[] args) {
String str = "TOM:89|JERRY:90|TONY:78";
String[] newstr = str.split("|");
System.out.println(Arrays.toString(newstr));
}
}我想把字符串拆分成[TOM:89, JERRY:90, TONY:78],但上面的代码运行出来确是
[, T, O, M, :, 8, 9, |, J, E, R, R, Y, :, 9, 0, |, T, O, N, Y, :, 7, 8]这时为什么?

解决方案 »

  1.   

    split的参数是regex, | 是个元字符,需要转义
      

  2.   

    String[] newstr = str.split("\\|");split参数为正则定义字符串
      

  3.   

    参看:
    package com.han;import java.util.Vector;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class SplitAndMatcher {
    public static void main(String[] args) {
    String str = "G11G12J1J2";

    /* If n is zero then the pattern will be applied as many times as
     * possible, the array can have any length, and trailing empty 
     * strings will be discarded. */
    String[] splitResult = Pattern.compile("(?=[a-zA-z])(?<=[0-9])").split(str, 0);
    System.out.println("The splitResult length is: " + splitResult.length);
    for (String e : splitResult) {
    System.out.println(e);
    }

    /* regex = regular expression */
    String[] splitResult2 = str.split("(?<=[0-9])(?=[a-zA-z])");
    System.out.println("The splitResult2 length is: " + splitResult2.length);
    for (String e : splitResult2) {
    System.out.println(e);
    }

    /* regex = regular expression */
    String[] splitResult3 = str.split("(?<=\\d)(?=[a-zA-z])");
    System.out.println("The splitResult3 length is: " + splitResult3.length);
    for (String e : splitResult3) {
    System.out.println(e);
    }

    /* X+ X, one or more times */
    Matcher matcher = Pattern.compile("[a-zA-Z]+\\d+").matcher(str);
    Vector<String> vector = new Vector<>();
    while (matcher.find()) {
    vector.add(matcher.group());
    }
    System.out.println("The matcher length is: " + vector.size());
    for (int j = 0; j < vector.size(); j++) {
    System.out.println(vector.get(j));
    }

    Matcher matcher2 = Pattern.compile("[a-zA-Z]+[0-9]+").matcher(str);
    Vector<String> vector2 = new Vector<>();
    while (matcher2.find()) {
    vector2.add(matcher2.group());
    }
    System.out.println("The matcher2 length is: " + vector2.size());
    for (int j = 0; j < vector2.size(); j++) {
    System.out.println(vector2.get(j));
    }
    }
    }
      

  4.   

    向楼上几位说的,转义一下就好了String[] newstr = str.split("\\|");