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

I am looking to create a single regex statement that is generally case insensitive, but, within the statement, demands a certain case. For example, I want to match a general pattern like this:

A) Title of paragraph

But dont want to match this:

a) Title of paragraph

The trouble is, the "title of paragraph" portion needs to be case insensitive, so, I want the statement to also match this

A) TiTLE of PARagraPh

but not this:

a) TiTLE of PARagraPh

Is there any way to accomplish this in a single regex statement? If I turn the "i" pattern modifier on, is there any way to turn it off for a small portion of the regular expression (the "A)") portion? Thanks.

Replies are listed 'Best First'.
Re: Selective Case sensitivity
by toolic (Bishop) on Feb 18, 2012 at 19:59 UTC
    Extended Patterns
    use warnings; use strict; while (<DATA>) { chomp; if (/A\) (?i:Title)/) { print "$_: matches\n"; } else { print "$_: does not match\n"; } } __DATA__ A) title a) title A) TItlE

    prints:

    A) title: matches a) title: does not match A) TItlE: matches
Re: Selective Case sensitivity
by davido (Cardinal) on Feb 18, 2012 at 19:59 UTC

    Yes, you can do that. Here's a simple example:

    my @strings = ( 'abBbBBbb', 'AbBbBBbb', ); foreach my $string ( @strings ) { if( $string =~ m/(?-i:a)b+/i ) { print "$string matched.\n"; } else { print "$string didn't match\n"; }

    In particular, the (?flags:PATTERN) construct as documented in perlre is what you're after. To turn on case sensitivity for a submatch where it's off in a broader scope you would say (?i:PATTERN), and to turn it off for a submatch (where it's on in a broader scope) you would say (?-i:PATTERN).


    Dave

Re: Selective Case sensitivity
by LonelyPilgrim (Beadle) on Feb 18, 2012 at 19:57 UTC

    How about this?

    /[A-Z]\) (?i:title of paragraph)/

    That should make the string with the parens case-insensitive, while leaving the stuff outside case sensitive.