在java中按字符串拆分字符串

时间:2011-03-14 08:49:38

标签: java regex string split

我从网上得到一个字符串,如下所示:

Latest Episode@04x22^Killing Your Number^May/15/2009

然后我需要将04x22Killing Your NumberMay/15/2009存储在不同的变量中,但它不起作用。

String[] all = inputLine.split("@");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);

现在它只存储NextNr,整个字符串

04x22^Killing Your Number^May/15/2009

有什么问题?

5 个答案:

答案 0 :(得分:32)

String.split(String regex)

论证是一个regualr表达式,^在那里有特殊含义; “锚定到开始”

你需要这样做:

String[] need = all[1].split("\\^");

通过逃避^你说“我的意思是'^''

答案 1 :(得分:22)

如果您有分隔符,但不知道它是否包含特殊字符,则可以使用以下方法

String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);

答案 2 :(得分:7)

使用番石榴,你可以优雅而快速地完成它:

private static final Splitter RECORD_SPLITTER = Splitter.on(CharMatcher.anyOf("@^")).trimResults().omitEmptyStrings();

...

Iterator<String> splitLine = Iterables.skip(RECORD_SPLITTER.split(inputLine), 1).iterator();

show.setNextNr(splitLine.next());
show.setNextTitle(splitLine.next());
show.setNextDate(splitLine.next());

答案 3 :(得分:1)

public static String[] split(String string, char separator) {
    int count = 1;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator)
            count++;
    String parts[] = new String[count];
    int partIndex = 0;
    int startIndex = 0;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator) {
            parts[partIndex++] = string.substring(startIndex, index);
            startIndex = index + 1;
        }
    parts[partIndex++] = string.substring(startIndex);
    return parts;
}

答案 4 :(得分:1)

String input = "Latest Episode@04x22^Killing Your Number^May/15/2009";

//split will work for both @ and ^
String splitArr[] = input.split("[@\\^]");

/*The output will be,
 [Latest Episode, 04x22, Killing Your Number, May/15/2009]
*/
System.out.println(Arrays.asList(splitArr));