java中按字符分割字符串

java中按字符分割字符串,java,regex,string,split,Java,Regex,String,Split,我从网上得到一个字符串,如下所示: Latest Episode@04x22^Killing Your Number^May/15/2009 然后我需要在不同的变量中存储04x22、Killing Your Number和May/15/2009,但它不起作用 String[] all = inputLine.split("@"); String[] need = all[1].split("^"); show.setNextNr(need[0]); show.setNextTitle(need

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

Latest Episode@04x22^Killing Your Number^May/15/2009
然后我需要在不同的变量中存储
04x22
Killing Your Number
May/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
怎么了?

String.split(String regex)

参数是一个常规表达式,
^
在这里有特殊含义;“锚定到开始”

您需要执行以下操作:

String[]need=all[1]。拆分(\\^)


通过转义
^
您说的是“我是指字符“^”

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

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

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

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());
private static final Splitter RECORD\u Splitter=Splitter.on(CharMatcher.anyOf(“@^”).trimResults().omitEmptyStrings();
...
Iterator splitLine=Iterables.skip(RECORD_SPLITTER.split(inputLine),1.Iterator();
show.setNextNr(splitLine.next());
show.setnextitle(splitLine.next());
show.setNextDate(splitLine.next());
公共静态字符串[]拆分(字符串、字符分隔符){
整数计数=1;
对于(int index=0;index
在正则表达式上进行拆分是最慢的。看一看Guava的Splitter类。通常(或者说…总是),建议某人在他们的项目中包含一个巨大的依赖项,这个依赖项可以节省几纳秒的时间,而你实际上并不关心,一点也不重要。。。这可不是什么好建议。另请参阅:Premature optimization.Guava是一个设计良好的通用库,它很好地补充了jre库。它不是“巨人”,也不仅仅对这一个问题有用。顺便说一句,String.split()每次执行时都编译正则表达式。在测试和初始化之外使用它是非常不鼓励的。您能解释一下这是如何回答这个问题的吗?字符串可以根据多个条件进行拆分。在这里,我使用@和^来拆分字符串。它既可以用作分隔符,也可以分割字符串。
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;
}
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));