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

this looks like a problem that should be easily solved with a regular expression, but i'm stuck :-( given a variable that might look like this:

$x='see the 9 brown foxes. they are certainly fast.';

the string is two sentences. '9' may not always be 9...but 8 or 7 or...but always a number. and the same goes for 'certainly' -- it could be any word.

certainly, something could be written that looks at $x enough times to have a sufficient degree of confidence that there is a string match. (eg, match on 'see the ' and then match on 'brown foxes' and match ong 'they certainly') but there is no elegance and little efficiency in that method.

is there a better way? - d

Replies are listed 'Best First'.
Re: searching a string with variable data
by borisz (Canon) on Nov 29, 2004 at 23:40 UTC
    # $_ contains a sentence. use \d+ for more numbers or \w+ for words if ( /see the \d brown foxes\. they are certainly fast\./ ) { # do something }
    Boris

      or, if you need to know the number, note the parens around the \d:

      my $count; if (($count) = /see the (\d) brown foxes/) { print("There are $count foxes. Let's go hunting!$/"); }

      Also, use \d+ if you want to match one or more digits, instead of just one.

      Lets not forget the 'certainly':
      if ( /see the \d brown foxes\. they are \w+ fast\./ ) { # do something }
      or with capturing (like ikegami pointed out)
      my ($count, $word); if (($count, $word) = /see the (\d) brown foxes\. they are (\w+) fast\ +./) { print("There are $count foxes. Let's go hunting!$/"); }
Re: searching a string with variable data
by rupesh (Hermit) on Nov 30, 2004 at 03:28 UTC

    One of the many things that can get you started on Perl Regular Expressions:
    perldoc perlre and
    perldoc perlretut

    Cheers,
    Rupesh.