Splitting a string in java on more than one symbol
Solution 1
String.split
takes a regular expression as argument.
This means you can alternate whatever symbol or text abstraction in one parameter in order to split your String
.
See documentation here.
Here's an example in your case:
String toSplit = "a+b-c*d/e=f";
String[] splitted = toSplit.split("[-+*/=]");
for (String split: splitted) {
System.out.println(split);
}
Output:
a
b
c
d
e
f
Notes:
- Reserved characters for
Pattern
s must be double-escaped with\\
. Edit: Not needed here. - The
[]
brackets in the pattern indicate a character class. - More on
Pattern
s here.
Solution 2
You can use a regular expression:
String[] tokens = input.split("[+*/=-]");
Note: -
should be placed in first or last position to make sure it is not considered as a range separator.
Solution 3
You need Regular Expression. Addionaly you need the regex OR
operator:
String[]tokens = Stringname.split("\\+|\\-|\\*|\\/|\\=");
Solution 4
For that, you need to use an appropriate regex statement. Most of the symbols you listed are reserved in regex, so you'll have to escape them with \
.
A very baseline expression would be \+|\-|\\|\*|\=
. Relatively easy to understand, each symbol you want is escaped with \
, and each symbol is separated by the |
(or) symbol. If, for example, you wanted to add ^
as well, all you would need to do is append |\^
to that statement.
For testing and quick expressions, I like to use www.regexpal.com
![Saumyaraj](https://i.stack.imgur.com/fuoD9.jpg?s=256&g=1)
Saumyaraj
Updated on August 06, 2020Comments
-
Saumyaraj almost 4 years
I want to split a string when following of the symbols encounter "+,-,*,/,=" I am using split function but this function can take only one argument.Moreover it is not working on "+". I am using following code:-
Stringname.split("Symbol");
Thanks.
-
Mena almost 11 years@RohitJain yep, just realized. I've edited my answer, thanks for pointing out.
-
Mena almost 11 years@saumyaraj I don't understand your question?
-
jlordo almost 11 years
input.split("[+*-/=]");
also includes,
and.
. Just split"a,b.c"
as an example, because the range from*
to/
includes those characters. -
jlordo almost 11 years
input.split("[+*/-=]");
even includes digits, the colon, semicolon and the<
symbol. -
jlordo almost 11 yearsThe dash inside a character class is always considered a range seperator, except if it's in the first or last position.
-
Saumyaraj almost 11 yearsI mean that when i use "+" in split function it showed me error something like "Dangling meta character". Can u explain a bit about this error?Thanks
-
Mena almost 11 years@saumyaraj yes. That is a meta-character, as in, a reserved character for a
Pattern
. It indicates a quantifier (see the Pattern page for more info). It'll work ok in a character class, but will need to be escaped if interpreted as literal "+" outside a character class. In your case, just try double escaping it as\\+
instead of+
.