Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: string split by regexp to get only integers

Tags:

java

string

split

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.

like image 354
Dragon Avatar asked Mar 04 '14 11:03

Dragon


3 Answers

You could try filtering out unwanted elements first and then split:

String filtered = str.replaceAll("[^0-9,]","");
String[] numbers = filtered.split(",");
like image 136
NeplatnyUdaj Avatar answered Nov 20 '22 06:11

NeplatnyUdaj


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.

like image 2
slim Avatar answered Nov 20 '22 04:11

slim


Actually split function returns an array of string,That's why you getting this [].

Use replace method to do this.

like image 1
saravanakumar Avatar answered Nov 20 '22 04:11

saravanakumar