regexp that ignore case or check the case based on a variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pierre

    regexp that ignore case or check the case based on a variable

    Hello,

    I would like to write a regexp that can be either case sensitive or that can
    ignore the case based on a variable (value would be either 'i' or '').
    For instance in the below code the variable is $case.
    I can't make that piece of code working fine. Anyone can help please ?

    my $str = "Hello World!";
    my $pattern "hello";
    my $case = "i";

    if ($str =~ s/${pattern}/${case}) {
    print "match!\n";
    }


    Thank you,
    Pierre.


  • cyber1
    New Member
    • Oct 2005
    • 1

    #2
    Pierre-

    You seem to have some other language mixed in here.
    I'm not clear on what it is you want.

    But try these:
    Code:
    my $str = "Hello World!";
    my $pattern = "hello";
    
    if ($str !~ m/$pattern/g){
    print "no match1!\n";
    }
    
    ##ignore case
    if (lc($str) =~ m/$pattern/g){
    print "match2!\n";
    }
    
    ##use case option
    if ($str =~ m/$pattern/gi){
    print "match3!\n";
    }
    More on Perl Regexp:


    -Bill

    Comment

    • Lars Kellogg-Stedman

      #3
      Re: regexp that ignore case or check the case based on a variable

      > I would like to write a regexp that can be either case sensitive or that can[color=blue]
      > ignore the case based on a variable (value would be either 'i' or '').
      > For instance in the below code the variable is $case.
      > I can't make that piece of code working fine. Anyone can help please ?
      >
      > my $str = "Hello World!";
      > my $pattern "hello";
      > my $case = "i";
      >
      > if ($str =~ s/${pattern}/${case}) {
      > print "match!\n";
      > }[/color]

      The above code doesn't actually run, but I'm assuming that was just typos
      when you posted it. It helps to put the code in a file and test it first.

      As for solving your regex question, you might want to take a look at:

      perldoc perlre

      Read the section entitled "Extended Patterns". You can set regex flags
      (such as "i" for "ignore case") in the pattern itself. For example:

      my $str = "Hello World!";
      my $case = "i";
      my $pattern = "(?$case)hello" ;

      if ($str =~ /${pattern}/) {
      print "match!\n";
      }

      -- Lars

      --
      larsks@hotmail. com

      Comment

      Working...