in reply to Regular expression help: why does this not match?

'?' is a regex metacharacter for optional. It doesn't match a literal '?'.

'.' is also, but it will only surprise you later. It does match literal '.'.

You can write,

if ($a =~ /\Q$b\E/) { # . . . }
to get all characters in $b taken as literal.

BTW, $a and $b are special to sort, so shouldn't be chosen as user variable names.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Regular expression help: why does this not match?
by lokiloki (Beadle) on Jan 18, 2007 at 23:00 UTC
    yes, i figured that... so if i have a very long string that contains multiple possible regex metacharacters, how can i do a match and tell that match to "ignore" any such metacharacters? or do i have to process the string first and backslash all of them??

      Or don't use a regexp at all.

      $a =~ /^\Q$b\E\z/
      is equivalent to
      $a eq $b

      $a =~ /\Q$b\E/
      is equivalent to
      index($a, $b) >= 0

      Case-insensitive versions:

      $a =~ /^\Q$b\E\z/i
      is equivalent to
      lc($a) eq lc($b)

      $a =~ /\Q$b\E/i
      is equivalent to
      index(lc($a), lc($b)) >= 0

      quotemeta or \Q as I added to my original reply.

      After Compline,
      Zaxo