Reputation: 35
I need help making a delimiter for multiple characters
I need a String delimiter for these characters
( ) " ; : , ? ! .
I've tried:
private String delimiter = "()\":;,?!.";
private String delimiter = "[()\":;,?!.]";
private String delimiter = "\\(\\)\"\\:\\;\\,\\?\\!\\.";
Seems I can only make them work one at a time.. Any insight is greatly appreciated.
If it matters this is how its going into array:
foo = line.split(delim);
Upvotes: 1
Views: 49
Reputation: 17595
Almost there with nr. 3
@Test
public void delim() {
String delimiter = "[\\(\\)\"\\:\\;\\,\\?\\!\\.]";
String[] split = "Hello(World)How:are;You;doing,today?You!sir.I mean"
.split(delimiter);
System.out.println(Arrays.toString(split));
}
Output
[Hello, World, How, are, You, doing, today, You, sir, I mean]
You missed the square brackets.
To avoid all the quoting you may use Pattern#quote
String delimiter = "[" + Pattern.quote("()\":;,?!.") + "]";
Returns a literal pattern String for the specified String. This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.
Upvotes: 3
Reputation: 4722
|
is required between:
delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\."
Upvotes: 2
Reputation: 12568
If you want to split on any of those characters, you can separate each one with an alternation: |
. Otherwise, the string will only be split when all of those characters are present.
String delimiter = "\\(|\\)|\"|\\:|\\;|\\,|\\?|\\!|\\.";
Also, you're unnecessarily escaping a few characters, this would also work:
String delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\.";
Upvotes: 3