Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to get first number in string with other characters

Tags:

java

regex

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

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

Thank you.

like image 363
ratsimihah Avatar asked Oct 21 '11 19:10

ratsimihah


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you get a number from a string in regex?

To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


9 Answers

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

like image 192
hair raisin Avatar answered Oct 05 '22 05:10

hair raisin


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));
    }
like image 25
Victor Sorokin Avatar answered Oct 05 '22 06:10

Victor Sorokin


Just

([0-9]+) .* 

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

like image 31
Pierre Lab Avatar answered Oct 05 '22 07:10

Pierre Lab


Assuming there's always a space between the first two numbers, then

preg_match('/^(\d+)/', $number_string, $matches);
$number = $matches[1]; // 100

But for something like this, you'd be better off using simple string operations:

$space_pos = strpos($number_string, ' ');
$number = substr($number_string, 0, $space_pos);

Regexs are computationally expensive, and should be avoided if possible.

like image 37
Marc B Avatar answered Oct 05 '22 07:10

Marc B


the below code would do the trick.

Integer num = Integer.parseInt("100 2011-10-20 14:28:55");
like image 30
Vivek Viswanathan Avatar answered Oct 05 '22 07:10

Vivek Viswanathan


[0-9] means the numbers 0-9 can be used the + means 1 or more times. if you use [0-9]{3} will get you 3 numbers

like image 20
orangegoat Avatar answered Oct 05 '22 05:10

orangegoat


Try ^(?'num'[0-9]+).*$ which forces it to start at the beginning, read a number, store it to 'num' and consume the remainder without binding.

like image 20
Daniel Moore Avatar answered Oct 05 '22 06:10

Daniel Moore


This string extension works perfectly, even when string not starts with number. return 1234 in each case - "1234asdfwewf", "%sdfsr1234" "## # 1234"

    public static string GetFirstNumber(this string source)
    {
        if (string.IsNullOrEmpty(source) == false)
        {
            // take non digits from string start
            string notNumber = new string(source.TakeWhile(c => Char.IsDigit(c) == false).ToArray());

            if (string.IsNullOrEmpty(notNumber) == false)
            {
                //replace non digit chars from string start
                source = source.Replace(notNumber, string.Empty);
            }

            //take digits from string start
            source = new string(source.TakeWhile(char.IsDigit).ToArray());
        }
        return source;
    }
like image 37
Martin Topolsky Avatar answered Oct 05 '22 06:10

Martin Topolsky


NOTE: In Java, when you define the patterns as string literals, do not forget to use double backslashes to define a regex escaping backslash (\. = "\\.").

To get the number that appears at the start or beginning of a string you may consider using

^[0-9]*\.?[0-9]+       # Float or integer, leading digit may be missing (e.g, .35)
^-?[0-9]*\.?[0-9]+     # Optional - before number (e.g. -.55, -100)
^[-+]?[0-9]*\.?[0-9]+  # Optional + or - before number (e.g. -3.5, +30)

See this regex demo.

If you want to also match numbers with scientific notation at the start of the string, use

^[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?        # Just number
^-?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?      # Number with an optional -
^[-+]?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?   # Number with an optional - or  +

See this regex demo.

To make sure there is no other digit on the right, add a \b word boundary, or a (?!\d) or (?!\.?\d) negative lookahead that will fail the match if there is any digit (or . and a digit) on the right.

like image 30
Wiktor Stribiżew Avatar answered Oct 05 '22 07:10

Wiktor Stribiżew