The line below splits my string on (.
), (,
), (:
) and newline (\\n
) characters.
String[] textPhrases = text.sp
I need to split on hyphen characters too, but this does not work...What am I missing or doing wrong?
To answer your question first off on what's wrong in this picture, you have forward slashes inside of your character class around your hyphen. Instead you should be using the escape sequence character (\\
)
[.,:/-/\\n]
^^^ Remove these and replace with the escape sequence character (\\-)
Within a character class []
, you can place a hyphen (-
) as the first or last character. You may also escape it ([.,:\\-\n]
) to add the hyphen in order to be matched.
String s = "hey,hi.foo:bar\nbaz-quz";
String[] parts = s.split("[.,:\n-]");
System.out.println(Arrays.toString(parts));
Output
[hey, hi, foo, bar, baz, quz]