Embedding Regex in Strings 
Author Message
 Embedding Regex in Strings

Hi list,

I was able to embed a regular expression in a string and later perform a
pattern match on it(see below). The regular expression part of $c_string is
the '\s+' to match one or more whitespace characters. Can anyone provide a
brief explanation on how/why this works?

my $c_string = '#pragma\s+BSS';   # Look for these lines of C code
my $line = '#pragma    BSS("something")';

if( $line =~ m/^$c_string\s*\(.+?\)/i)
{
   print "Pattern matching occurs after interpolation?\n";

Quote:
}

Thank you,
Larry S.


Mon, 17 May 2004 22:33:39 GMT  
 Embedding Regex in Strings
The string is interpolated before the matching takes place.

Lao



Mon, 17 May 2004 23:19:57 GMT  
 Embedding Regex in Strings

Quote:

>I was able to embed a regular expression in a string and later perform a
>pattern match on it(see below). The regular expression part of $c_string is
>the '\s+' to match one or more whitespace characters. Can anyone provide a
>brief explanation on how/why this works?

Why not? It's useful.

You must take care that the string itself looks exactly like what you
would type directly in the regex. That often means: doubling the
backslashes.

        $re = '\\\\';
        $_ = '\\' x 10;
        print /($re)/;

This will try one match of a number of backslashes. Can you predict how
many?

One.

That is because after the assignment, $re will contain two backslashes.
and /(\\)/ matches one backlash.

If your perl is recent enough (this must mean "under a few years old",
by now), you can also use the qr() operator, which currently doesn't
actually compile a regex, but instead just quotes the regex as if you
just typed it in.

        $re = qr/\\/;
        print $re;

This prints

        (?-xism:\\)

which is the double backslash, and all modifiers disabled. So:

        $re = qr/\\\\/;
        $_ = '\\' x 10;
        print /($re)/;

prints two backslashes, just as if you had done

        print /(\\\\)/;

Oh, and check out what the /o modifier does. If you couldn't use
interpolation inside a regex, this modifier wouldn't exist.
Documentation is in perlop, but not in perlre, likely because /o doesn't
modify the meaning of the regex itself (= what is between the slashes),
but only the behaviour of the /PATTERN/ AKA m/PATTERN/ operator.

--
        Bart.



Tue, 18 May 2004 00:26:11 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Help tokenizing strings w/ embedded quoted strings

2. hairy regex - embedded parentheses

3. regex: embedded spaces

4. quoteSplit - Split string into array with embedded quotes

5. (regexp) palindromes embedded in a string

6. printing strings with embedded nulls

7. Syntax error string when embedding in C++

8. How to embed special characters in replacement string?

9. Pattern-matching when strings have embedded "$"

10. Embedding Hex char in string

11. String with embedded spaces.

12. how to embed sub call in string?

 

 
Powered by phpBB® Forum Software