Regex to get first number in string with other characters

Just

([0-9]+) .* 

If you always have the space after the first number, this will work


/^[^\d]*(\d+)/

This will start at the beginning, skip any non-digits, and match the first sequence of digits it finds

EDIT: this Regex will match the first group of numbers, but, as pointed out in other answers, parseInt is a better solution if you know the number is at the beginning of the string


Try this to match for first number in string (which can be not at the beginning of the string):

    String s = "2011-10-20 525 14:28:55 10";
    Pattern p = Pattern.compile("(^|\\s)([0-9]+)($|\\s)");
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println(m.group(2));
    }

Tags:

Java

Regex