I have a string that\'s like this: 1|\"value\"|;
I want to split that string and have chosen |
as the separator.
My code looks like
Pattern.compile("|").splitAsStream(String you want to split).collect(Collectors.toList());
String.split() uses regex, so you need to escape the '|' like .split("\\|");
You have to escape the |
because it has a special meaning in a regex. Have a look at the split(..) method.
String[] sep = line.split("\\|");
The second \
is used to escape the |
and the first \
is used to escape the second \
:).
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.
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]
}
}
|
is treated as an OR
in RegEx. So you need to escape it:
String[] separated = line.split("\\|");
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;
}
}