What is regex modifiers (/i /m /s /x) in Perl?

In Perl, regex modifiers are used to change the behavior of regular expressions. The following are common modifiers:

  • /i: Case-insensitive matching. It makes the regex match letters regardless of their case.
  • /m: Multiline matching. It changes the behavior of the ^ and $ anchors to match the start and end of each line within a string, rather than just the start and end of the entire string.
  • /s: Single-line matching. It allows the dot (.) to match newline characters, making it possible to match across multiple lines.
  • /x: Extended mode. It allows you to include whitespace and comments in your regex for better readability, ignoring extra spaces and comments after a # symbol.

Here's an example demonstrating these modifiers:

$pattern = qr/^hello/i; // Case insensitive match if ("Hello there!" =~ $pattern) { print "Matched!\n"; } $multiline_text = "line1\nline2\nline3"; if ($multiline_text =~ /line2/m) { print "Found line2 in multiline text!\n"; } $multi_line_pattern = qr/line1.*line3/s; // Dot matches across lines if ($multi_line_pattern =~ /$multi_line_pattern/) { print "Matched across multiple lines!\n"; } $extended_pattern = qr/ \bfoo\b # This is a comment /x; if (" foo " =~ $extended_pattern) { print "Matched foo with extended pattern!\n"; }

regex modifiers Perl regex regex examples case-insensitive matching multiline matching single-line matching extended regex