samy ben
samy ben

Reputation: 155

Regex numbers after letters

I have this regex:

/\d+(?!\d| |[a-zA-Z])/gm

and this string:

,98dépo 58 cou54lis 
GU966,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700,2800,2900,3000
1600.00,1841.00,1882.80,1898.50,1914.30,1930.00,1945.80,1993.40,2009.20,2028.50,2044.30,2061.50,2095.30,2111.1

I don't want to match the any numbers in ',98dépo 58 cou54lis GU966' but all others yes.

How can I do this?
thanks

Upvotes: 2

Views: 84

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

Pattern: ~[\v,]\K\b[.\d]+\b~

Pattern Demo

All of your valid numbers have a comma or vertical white-space before them.

$string=',98dépo 58 cou54lis 
GU966,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700,2800,2900,3000
1600.00,1841.00,1882.80,1898.50,1914.30,1930.00,1945.80,1993.40,2009.20,2028.50,2044.30,2061.50,2095.30,2111.1';

var_export(preg_match_all('~[\v,]\K\b[.\d]+\b~',$string,$out)?$out[0]:[]);

Output:

array (
  0 => '1800',
  1 => '1900',
  2 => '2000',
  3 => '2100',
  4 => '2200',
  5 => '2300',
  6 => '2400',
  7 => '2500',
  8 => '2600',
  9 => '2700',
  10 => '2800',
  11 => '2900',
  12 => '3000',
  13 => '1600.00',
  14 => '1841.00',
  15 => '1882.80',
  16 => '1898.50',
  17 => '1914.30',
  18 => '1930.00',
  19 => '1945.80',
  20 => '1993.40',
  21 => '2009.20',
  22 => '2028.50',
  23 => '2044.30',
  24 => '2061.50',
  25 => '2095.30',
  26 => '2111.1',
)

This adjustment of apokryfos' method returns the same expected result as my regex method.

var_export(array_filter(explode(',',str_replace(PHP_EOL,',',$string)),'is_numeric'));

It merely prepares the string for explosion by converting newline characters to commas.

Upvotes: 2

apokryfos
apokryfos

Reputation: 40653

Use a sane solution:

$numbers = array_filter(explode(",", str_replace(["\r\n","\n","\r"],",", $string)), 'is_numeric');

Demo: http://sandbox.onlinephpfunctions.com/code/958360336537ba5c4c99cba7e18419738045f407

Upvotes: 3

Vladimir
Vladimir

Reputation: 1391

You can use this regexp:

/\n?([,\n](\d{1,}\.?\d{0,}))/

Usage:

$pattern = '/\n?([,\n](\d{1,}\.?\d{0,}))/';
preg_match_all($pattern, $str, $match);

$values = $match[2];

Upvotes: 0

Related Questions