How to extract all integer values ​​from a string using regular expression?

I am trying to learn regex. I have a line:

$x = "5ft2inches";

How can I read [5,2] into an array using regex?

+3
source share
8 answers

If you assume that the string will be of the form "{number} ft {number} inches", you can use preg_match () :

preg_match('/(\d+)ft(\d+)inches/', $string, $matches);

(\d+)will match a string of one or more digits. The brackets indicate preg_match()to put matching numbers in a variable $matches(the third argument of the function). The function will return 1 if it made a match, from 0 if it is not.

$matches :

Array
(
    [0] => 5ft2inches
    [1] => 5
    [2] => 2
)

- , . , :

$array = array($matches[1], $matches[2]);
+5

Perl:

#!/usr/bin/perl

use strict;
use warnings;

my $x = "5ft2inches";
my %height;
@height{qw(feet inches)} = ($x =~ /^([0-9]+)ft([0-9]+)inches$/);

use Data::Dumper;
print Dumper \%height;

:

$VAR1 = {
          'feet' => '5',
          'inches' => '2'
        };

, split:

@height{qw(feet inches)} = split /ft|inches/, $x;
+2

PHP, - ?

$numbers = preg_split('/[^0-9]+/', $x, -1, PREG_SPLIT_NO_EMPTY);
+2

/[0-9]+/, , , .

+1

, .

IE, : (\d+) (NB: , \d " " )

, , , , "5 2inches" "6ft2inches" "29Cabbages1Fish4Cows".

: (\d+)ft(\d+)inches

, ( ), , .

, . Cheat Sheet ( - ) ,

+1

You do not specify the language you use, so here is the general solution: you do not “extract” the numbers, you replace everything except the numbers with an empty string.

In C #, it will look like

string numbers = Regex.Replace(dirtyString, "[^0-9]", "");
0
source

You need to keep track of double-digit numbers.

/ \ d {1,2} /

may improve slightly for legs and inches. The maximum value of "2" should be increased to the required.

0
source
use `/[\d]/`
0
source

Source: https://habr.com/ru/post/1716166/


All Articles