I have to “translate” this preg_split code into a Java equivalent. I have tried a few things without success. Here’s the PHP code I am attempting to translate:
$str="1 [3 4 5] 6 7 [8 9] 4";
$chars = preg_split("^\[(.*?)\]||/ /^", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($chars as $key => $value) {
if(ord($value)!=0 && $value!=" "){
$res[]=$value;
}
}
print_r($res);
As you can see, my String input can be composed of any sequence of number chars, some of them being wrapped with [ ] brackets:
1 [3 4 5] 6 7 [8 9] 4
Brackets can be either at the beginning or end of the String, there’s no restriction on that.
Following the example above, result would look like this:
[0] = "1"
[1] => "3 4 5"
[2] => "6"
[3] => "7"
[4] => "8 9"
[5] => "4"
I’ve found some issues trying to translate the regular expression (looks like “\” fail as invalid escape sequence).
Rather than thinking of the problem as “splitting” I would try and come up with a regular expression that matches any single substring of the form you are looking for, then gather all matches of that expression, for example:
The bit to the left of the
|matches anything between square brackets, the bit to the right matches any other sequence of digits.Note that when you want to write a regular expression in a Java string literal you need to double the backslashes – the literal
"\\"represents a single character string containing one backslash.