I have a string: [1, 2, 3, 4]
. I need to get only integers 1 2 3 4
.
I tried the following splits:
str.split(",");
str.split("\\D\\s");
Both splits return four elements: [1 2 3 4], but I don't need these brackets [ ]
. What is wrong with split regexp?
updated
I had to mention that the case when each number is wrapped with [ ]
can occur.
You could try filtering out unwanted elements first and then split:
String filtered = str.replaceAll("[^0-9,]","");
String[] numbers = filtered.split(",");
Your code is doing exactly what you tell it: split the string using "," as a delimiter:
"[1, 2, 3]" => "[1" , " 2", " 3]"
You could massage the string into shape before using split()
- to remove the spaces and the square brackets. However a more direct, regex way to do it is to use a Matcher to scan through the input string:
Pattern pattern = Pattern.compile("(\\d+)\\D+");
ArrayList<String> list = new ArrayList<String>();
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
list.add(matcher.group(1));
}
// if you really need an array
String[] array = list.toArray(new String[0]);
This pattern (\d+)\D+
matches one or more digits, followed by one or more non-digits, and it captures the digits in a group, which you can access using matcher.group(1)
. It matches your input quite loosely; you could make it more specific (so that it would reject input in other forms) if you preferred.
Actually split function returns an array of string,That's why you getting this [].
Use replace method to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With