Reputation: 68
Find only the integers in a math equation...
5 + 5.5 + 6 / 2.0
I want to find the 5 and the 6 not the 5.5 or the 2.0 To find decimals I use \d+(.\d{1,})
I've tried \b\d+\b but that finds all the digits
Upvotes: 1
Views: 10425
Reputation: 2586
Could try this:
/(?:^|[^\.])(\d+)(?:\s+|$)/
Make sure a digit(s) does not start with a dot, or is the beginning of the string, and makes sure the digit(s) are followed by a space, or the end of the string.
Here is a PHP example in action:
preg_match_all('/(?:^|[^\.])(\d+)(?:\s+|$)/', '5 + 5.5 + 6 / 2.0 + 33 * 16', $matches);
var_dump($matches);
/* Var Dump:
array (size=2)
0 =>
array (size=4)
0 => string '5 ' (length=2)
1 => string ' 6 ' (length=3)
2 => string ' 33 ' (length=4)
3 => string ' 16' (length=3)
1 =>
array (size=4)
0 => string '5' (length=1)
1 => string '6' (length=1)
2 => string '33' (length=2)
3 => string '16' (length=2)
*/
So what was captured was 5, 6, 33, and 16 (I added some longer digits to ensure it works)
Upvotes: 0
Reputation: 949
You could try to look for all digits, that don't have a "." in front, and have whitespace afterwards, like so:
[^\.]([0-9]+)\s
Upvotes: 0
Reputation: 111219
You can use negative lookbehind and lookahead, if that's supported by your regular expression engine. The regular expression would be:
(?<!\.)\d+(?!\.)
The lookbehind ensures that the string of digits does not begin with a .
, so that something like .5
won't be matched. The lookahead ensures that the string of digits does not end with a .
, so that 5.
won't be matched.
Upvotes: 4