Input String is valor[x,y,z]
(value and range)
The range is optional .
make split
excluding those within [ ]
Example: 20[4Y,2W,4H] , 10[2Y,1W,5H]
- > 20[4Y,2W,4H]
and 10[2Y,1W,5H]
If the space only appears around the comma that separates values, you could use " , "
as a delimiter.
But if the range is optional, there could be values such as 20,10[2Y,1W,5H]
where you could not use the characters around the comma.
It can be addressed in 2 ways, both using a regex:
Separate in commas that are not followed by a ]
(when there is not a [
in the middle.
String[] elementos = data.split(" *, *+(?![^]\[]*])");
-
*, *+
any number of spaces, a comma, and any number of spaces.
-
(?![^]\[]*])
construction (?!
... )
is a negative inspection , or negative lookahead . Find that the current position is not followed by:
-
[^]\[]*
any characters that are not ]
ni [
-
]
and the closure of brackets that would mean that it is within a range.
Match with each of the parties (instead of doing a split)
For that we use a regular expression that matches the value and, optionally with each of the 3 values of the range:
(\d+)(?:\[(\d+)Y,(\d+)W,(\d+)H])?
In this way, we already have all the values separated.
Code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(\d+)(?:\[(\d+)Y,(\d+)W,(\d+)H])?";
final String texto = "1,2,3,20[4Y,2W,4H] , 10[2Y,1W,5H],4 , 5[10Y,20W,5H]";
// así se compila siempre un regex
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(texto);
//y así se buscan siempre todas las coincidencias
while (matcher.find()) {
//asignamos el valor capturado por cada grupo
String valor = matcher.group(1);
String rangoY = matcher.group(2);
String rangoW = matcher.group(3);
String rangoH = matcher.group(4);
//imprimimos en consola
System.out.printf("Valor: %3s - Y: %4s - W: %4s - H: %4s%n",valor,rangoY,rangoW,rangoH);
}
Result:
Valor: 1 - Y: null - W: null - H: null
Valor: 2 - Y: null - W: null - H: null
Valor: 3 - Y: null - W: null - H: null
Valor: 20 - Y: 4 - W: 2 - H: 4
Valor: 10 - Y: 2 - W: 1 - H: 5
Valor: 4 - Y: null - W: null - H: null
Valor: 5 - Y: 10 - W: 20 - H: 5
Demo: link