Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

extracting a substring?

by CHRYSt (Acolyte)
on Jan 16, 2002 at 23:06 UTC ( [id://139285]=perlquestion: print w/replies, xml ) Need Help??

CHRYSt has asked for the wisdom of the Perl Monks concerning the following question:

Ok, another noob question, but I can't find any info on how to do exactly this.
(I've found similar stuff, but I can't figure out how to modify it so it works.)

How can I extract a string from a larger string using regex, and put it into a variable? I'm searching for a string that's in an unknown place in the larger one, and is an unknown length. I'm specifically searching for the string:
alt="Version x.xx"
from a bunch of HTML

Replies are listed 'Best First'.
Re: extracting a substring?
by grep (Monsignor) on Jan 16, 2002 at 23:10 UTC
    You have 2 options that I can think of off the top of my head.

    Do an 'index' inside a 'substr'
    or a regex and capture the result to $1.

    Resources:
  • index
  • substr
  • perlre

    Example of index/substr solution:
    #!/usr/bin/perl -w use strict; my $look_for = 'foobar'; my $string = 'this whole script is foobared'; my $result = substr($string,index($string,$look_for),length($look_for) +); print $result;

    Attempt at the regex:
    $str =~ /(Version\s+\d+\.\d+)/; $result = $1;


    grep
    grep> cd pub grep> more beer
Re: extracting a substring?
by ehdonhon (Curate) on Jan 16, 2002 at 23:33 UTC

    In the example you gave above, you could do something like this (assuming the string you are checking is in $_):

    if ( /alt="Version (.\...)"/ ) { $version = $1; }

    You could also crunch that to this:

    ($version) = /alt="Version (.\...)"/;
Re: extracting a substring?
by dmouille (Novice) on Jan 16, 2002 at 23:34 UTC
    try this(I'm assuming that the x's represent digits):

    $string =~ m/(alt=\"Version \d.\d\d\")/; $substring = $1;
      Actually, that first line should be:

      $string =~ m/(alt=\"Version \d\.\d\d\")/;
Re: extracting a substring?
by CHRYSt (Acolyte) on Jan 17, 2002 at 00:01 UTC
    Well, now I run into the following problem:
    any time I try to use a regex, it returns
    Use of uninitialized value in pattern match (m//) at test.pl line 6.
      What is the code you are using?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://139285]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-19 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found