user1985273
user1985273

Reputation: 1967

Java - separate numbers from a string

I have a string that contains a few numbers (usually a date) and separators. The separators can either be "," or "." - or example 01.05,2000.5000

....now I need to separate those numbers and put into an array but I'm not sure how to do that (the separating part). Also, I need to check that the string is valid - it cannot be 01.,05.

I'm not asking for anyone to solve the thing for me (but if someone wants I appreciated it), just point me in the right direction :)

Upvotes: 1

Views: 549

Answers (7)

Bohemian
Bohemian

Reputation: 424983

To validate:

if (input.matches("^(?!.*[.,]{2})[\\d.,]+))

This regex checks that:

  • dot and comma are never adjacent
  • input is comprised only of digits, dots and commas

To split:

String[] numbers = input.split("[.,]");

Upvotes: 1

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

Try this:

String str = "01.05,2000.5000";
str = str.replace(".",",");
int number = StringUtils.countMatches(str, ",");
String[] arrayStr = new String[number+1];
arrayStr = str.split(",");

StringUtils is from Apache Commons >> http://commons.apache.org/proper/commons-lang/

Upvotes: 1

Prince John Wesley
Prince John Wesley

Reputation: 63688

Use regex to group and match the input

    String s = "01.05,2000.5000";       
    Pattern pattern = Pattern.compile("(\\d{2})[.,](\\d{2})[.,](\\d{4})[.,](\\d{4})");      
    Matcher m = pattern.matcher(s);

    if(m.matches()) {
        String[] matches = { m.group(1),m.group(2), m.group(3),m.group(4) };
        for(String match : matches) {
            System.out.println(match);
        }
    } else {
        System.err.println("Mismatch");
    }

Upvotes: 1

Jan Dörrenhaus
Jan Dörrenhaus

Reputation: 6717

If possible, I would use guava String splitter for that. It is much more reliable, predictable and flexible than String#split. You can tell it exactly what to expect, what to omit, and so on.

For an example usage, and a small rant on how stupid javas split sometimes behaves, have a look here: http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter

Upvotes: 1

dinox0r
dinox0r

Reputation: 16039

This is a way of doing it with StringTokenizer class, just iterate the tokens and if the obtained token is empty then you have a invalid String, also, convert the tokens to integers by the parseInt method to check if they are valid integer numbers:

import java.util.*;
public class t {
    public static void main(String... args)  { 
        String line = "01.05,2000.5000";
        StringTokenizer strTok = new StringTokenizer(line, ",.");
        List<Integer> values = new ArrayList<Integer>();
        while (strTok.hasMoreTokens()) {
            String s = strTok.nextToken();
            if (s.length() == 0) { 
                // Found a repeated separator, String is not valid, do something about it
            } 
            try { 
                int value = Integer.parseInt(s, 10);
                values.add(value);
            } catch(NumberFormatException e) { 
                // Number not valid, do something about it or continue the parsing 
            }
        }

        // At the end, get an array from the ArrayList
        Integer[] arrayOfValues = values.toArray(new Integer[values.size()]);

        for (Integer i : arrayOfValues) {
            System.out.println(i);
        }
    }
}

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135752

Iterate through an String#split(regex) generated array and check each value to make sure your source String is "valid".

In:

String src = "01.05,2000.5000";
String[] numbers = src.split("[.,]");

numbers here will be an array of Strings, like {"01", "05", "2000", "5000"}. Each value is a number.

Now iterate over numbers. If you find a index that is not a number (it's a number when numbers[i].matches("\\d+") is true), then your src is invalid.

Upvotes: 1

scgr
scgr

Reputation: 57

In order to separate the string, use split(), the argument of the method is the delimiter

array = string.split("separator");

Upvotes: 0

Related Questions