split a string by any symbol
-
14-07-2021 - |
Question
What is the regex that I should pass with String.split()
in order to split the string by any symbol?
Now, by any symbol I mean any of the following:
`~`, `!`, `@`, `#`, ...
Basically any non-letter and non-digit printable character.
Solution
You should use a non word i.e \W
\W
is inverse of \w
\W
is similar to [^a-zA-Z0-9_]
and so would match any non-word character except _
OR
you can simply use [^a-zA-Z0-9]
OTHER TIPS
You can try using this: -
str.split("[^a-zA-Z0-9]");
This will not include an underscore
.
\W
is equivalent to: - "[a-zA-Z0-9_]"
You could either be specific like Spring.split("[~!@$]")
or list the values you do not want to split upon Spring.split("[^\\w]")
You may want to use \W
or ^\w
. You may find more details here: Regex: Character classes
String str = "a@v$d!e";
String[] splitted = str.split("\\W");
System.out.println(splitted.length); //<--print 4
or
String str = "a@v$d!e";
String[] splitted = str.split("[^\\w]");
System.out.println(splitted.length); //<--print 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow