Reputation: 875
I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:
String str ="[email protected]||[email protected]||[email protected]";
i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.
StringTokenizer token = new StringTokenizer(str, "||");
The above code works fine.But not able to figure out why below string.split function not giving me expected result..
String[] strArry = str.split("\\||");
Where am i going wrong..?
Upvotes: 5
Views: 15990
Reputation: 614
For this you can follow two different approaches you can follow whichever suites you best:
Approach 1:
By Using String SPLIT functionality
String str = "a||b||c||d";
String[] parts = str.split("\\|\\|");
This will return you an array of different values after the split:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Approach 2:
By using PATTERN and MATCHER
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String str = "a||b||c||d";
Pattern p = Pattern.compile("\\|\\|");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("Found two consecutive pipes at index " + m.start());
}
This will give you the index positions of consecutive pipes:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Upvotes: 0
Reputation: 533
Try this
String yourstring="Hello || World";
String[] storiesdetails = yourstring.split("\\|\\|");
Upvotes: -1
Reputation: 2691
String.split()
uses regular expressions. You need to escape the string that you want to use as divider.
Pattern has a method to do this for you, namely Pattern.quote(String s)
.
String[] split = str.split(Pattern.quote("||"));
Upvotes: 17
Reputation: 8022
You can try this too...
String[] splits = str.split("[\\|]+");
Please note that you have to escape the pipe since it has a special meaning in regular expression and the String.split() method expects a regular expression argument.
Upvotes: 0