How to split word not a single character in Java?
I would like to split this string by a word "data::" not by single character. How?
String bla = "data::01000100010001000100data::0101001010101010101data::11111111111111111";
String result[] = bla.split("\\data::");
/*
* this outputs the whole string
* instead of only: 01000100010001000100*/
System.out.println(result[0]);
Note:
package test;
public class NewClass
{
public static void main(String[] args)
{
String bla = "data::0000data::1111data::010101";
// Try 1 - failed
String[] parta = bla.split("\\ddata::");
System.out.println(parta[0]);
System.out.println(parta[1]);
System.out.println(parta[2]);
// Try 2 - failed -- works
String[] partb = bla.split("data::");
System.out.println(partb[0]); // consider as empty
System.out.println(partb[1]); // starts from here
System.out.println(partb[2]);
// Try 3 - failed
String partc[] = bla.split("\\wda开发者_如何学运维ta::");
System.out.println(partc[0]);
System.out.println(partc[1]);
System.out.println(partc[2]);
}
}
Failed Output:
run:
data::000
111
010101
0000
1111
data::000
111
010101
BUILD SUCCESSFUL (total time: 0 seconds)
\\d
inside a string literal denotes a digit in regex. You need to split on simply this:
bla.split("data::")
Because there is no single digit followed by ata::
(the pattern: "\\data::"
), the entire string is returned by String.split(...)
.
Try Guava's Splitter class Splitter
Iterable<String> result = Splitter.on("data::").split(bla);
Ok, looking at the other responses might be overkill but worth checking out. It is a really nice tool since it allows things such as "omitEmptyStrings" and "trimResults".
String bla = "data::01000100010001000100data::0101001010101010101data::11111111111111111";
String result[] = bla.split("data::");
Test -
System.out.println(result[0]) //empty
System.out.println(result[1]) //01000100010001000100
精彩评论