| -----Original Message-----
| From: Rupert Heesom [mailto:[EMAIL PROTECTED]]
| Sent: Tuesday, September 11, 2001 6:00 PM
| To: HOLLAND-MORITZ,MARCUS " "(A-hsgGermany,ex1)
| Cc: '[EMAIL PROTECTED]'
| Subject: RE: Problems using REGEXP
|
|
| Thanks so much for the response, Marcus.
|
| Now I know why I was struggling. Sometimes I need human
| interaction to
| understand concepts besides just reading a book.
|
| More reply below -
|
| On 10 Sep 2001 13:51:23 +0200, HOLLAND-MORITZ,MARCUS
| (A-hsgGermany,ex1)
| wrote:
| >
| > Yes, there's a better way. Catch the digits with parentheses inside
| > the regex and evaluate the match in list context to get the result:
| >
| > -----------------------------------------------------------
| > $job{Ra} = 'Ra: 45k';
| >
| > if( ($x) = $job{Ra} =~ /(\d\d)/ ) {
| > print "the number is: $x\n";
| > }
| > else {
| > print "no number... :-(\n";
| > }
| > -----------------------------------------------------------
|
| I think I understand what you're doing here -
|
| The 'if' line captures the REGEXP & stores it in $x, then evaluates it
| using the 'if' condition.
The 'if' line performs a pattern match of $job{Ra} against /(\d\d)/,
puts the result into $x and uses $x for the condition.
| In this example is it important to have the parenthesis (brackets)
| around the '\d\d'?
Yes. The brackets 'catch' the content they encapsulate. If a regex
match is evaluated in list context (see below), it returns a list of
all catched subexpressions instead of only 0 or 1 for failure/success.
| Also why is "($x)" in brackets?
To force a list context for the regular expression match.
| I assume that /(\d\d)/ is finding one double-digit number in
| the string.
| What if I am looking for 2 numbers in the string? The REGEXP
| will find
| the first number, right? How do I go about finding the next number if
| any?
Say you have:
$string = 'some numbers: 42, 4711, 314';
Then you could extract all numbers using the /g modifier for regexes:
@numbers = $string =~ /(\d+)/g;
The array @numbers automatically provides list context for the match,
the parentheses catch one or more (+) digits (\d), and the /g modifier
makes the regex grab all matches.
print "@numbers\n";
will print:
42 4711 314
| --
| regs
| rupert
|
-- Marcus
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]