Regex to get first number in string with other characters

2022-09-02 00:31:50

I'm new to regular expressions, and was wondering how I could get only the first number in a string like . In this case, I'd want it to return , but the number could also be shorter or longer. 100 2011-10-20 14:28:55100

I was thinking about something like , but it takes every single number separately (100,2001,10,...)[0-9]+

Thank you.


答案 1
/^[^\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


答案 2

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));
    }