Search code examples
regexstringperlextract

Regex extract some specific number from string, tried several methods


I need to extract a specific number from string in variable; for example, $ex is having URLs like "https://www.google.com&r=12345&s=1&t=2", and I need to extract 12345 only. I tried these three regexes but it's not working.

  1. This one returning =12345=1=2.

    $example = $1 if( $ex=~ s/[^=\d]//g);
    
  2. This one returning null.

    $example = $1 if($ex=~ m/r\=([\d+])\&/i);
    
  3. This one returning null.

    $example = $1 if($ex=~ m/r\^=([\d+])\&/i)
    

Solution

  • use URI             qw( );
    use URI::QueryParam qw( );
    
    $url = URI->new($url);
    my $example = $url->query_param('r');  # Get first `r` arguments.
    my @example = $url->query_param('r');  # Get all `r` arguments.