Alex Rivera | Logout

Regex to get first number in string with other characters

Asked 2011-10-21T19:07:34.600
30

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.

Edit
Report

2 Answers

4

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.

answered 2011-10-21T19:10:42.070
2

the below code would do the trick.

Integer num = Integer.parseInt("100 2011-10-20 14:28:55");
answered 2011-10-21T19:10:05.213

Your Answer