I need to split a line of assembly code using split() method in Java. Here is a sample code:
String line = "Add a, b, c";
String[] parts = line.split("[\\s+,]");
System.out.println(Arrays.toString(parts));
OUTPUT:
[Add, a, , b, c]
I need the output to be like:
[Add, a, b, c]
for any of the following inputs:
String line = "Add a,b,c";
String line = "Add a ,b,c";
String line = "Add a, b,c";
String line = "Add a,b , c";
String line = "Add a , b , c";
or any similar cases.
What is the right regex to use in place of [\\s+,]?
The following should do it:
Your current regex matches exactly one space, or exactly one
+, or exactly one comma.The above regex matches one or more spaces and/or commas.
The difference is the placement of the
+: when it appears inside of a character class, it is interpreted literally.