kirvis
kirvis

Reputation: 79

Extracting all number from string and combining them using RegEx

I am using RegEx in combination with an online scraper to extract data from a website. The scraper allows you to use Reguar Expressions to extract only parts of the strings.

The strings I want to extract look like this:

€ 1.250.000 k.k.
€ 359.000 k.k.
€ 89.000 v.o.n.

The result I want to get is as follows:

1250000
359000
80000

The result needs to be stored as a number.

I am using the expression [\d.]+ now, but that includes the period. If I remove the period from the expression, it does not take the numbers after the period.

Any ideas on that?

N.B. The scraper I am using is import.io

Upvotes: 0

Views: 279

Answers (1)

Shafizadeh
Shafizadeh

Reputation: 10360

There is two ways, I explain them using both JavaScript and PHP languages.

First approach:

Remove all non-numeric values, then all the rest is what you need:

JavaScript:

var str = "€ 1.250.000 k.k.";
    str = str.replace(/\D+/g, '');
document.write(str);

PHP:

$str = "€ 1.250.000 k.k.";
echo preg_replace("/\D+/", "", $str);

Online Demo


Second approach:

Extract all numbers from string and join them together to make expected number:

JavaScript:

var str = "€ 1.250.000 k.k.";
    str = str.match(/\d/g).join("");
document.write(str);

PHP:

$matches = array();
$str = "€ 1.250.000 k.k.";
$str = preg_match_all('/\d/', $str, $matches);
$str = implode("", $matches[0]);
echo $str;

Online Demo

Upvotes: 1

Related Questions