What is the difference between single line mode and multiline mode in Regular expressions?

Hi All,

Can please let me know what is the difference between the single line mode and multi line mode in regular expresions?

Thanks,
Chidhambaram B

If the stuff you need to see is on more than one line, you need to bring the multiple lines into the purview of one regex, like using N in sed to add lines to the buffer. There are additional regex for this situation, like '\n', and commands, like sed P.

Google says Regex Tutorial - Start and End of String or Line Anchors

Using ^ and $ as Start of Line and End of Line Anchors
If you have a string consisting of multiple lines, like first line\nsecond line (where \n indicates a line break), it is often desirable to work with lines, rather than the entire string. Therefore, all the regex engines discussed in this tutorial have the option to expand the meaning of both anchors. ^ can then match at the start of the string (before the f in the above string), as well as after each line break (between \n and s). Likewise, $ will still match at the end of the string (after the last e), and also before every line break (between e and \n).
In text editors like EditPad Pro or GNU Emacs, and regex tools like PowerGREP, the caret and dollar always match at the start and end of each line. This makes sense because those applications are designed to work with entire files, rather than short strings.
In all programming languages and libraries discussed on this website , except Ruby, you have to explicitly activate this extended functionality. It is traditionally called "multi-line mode". In Perl, you do this by adding an m after the regex code, like this: m/^regex$/m;. In .NET, the anchors match before and after newlines when you specify RegexOptions.Multiline, such as in Regex.Match("string", "regex", RegexOptions.Multiline).

1 Like

Thanks very much for your response.

Can you please clear my question below?

I tried the below perl one-line commands but I could not get feel the result as expected.

echo "One 1\nTwo 2\nThree 3" | perl -ne 'print if m/^Two (\d+)$/m'

echo "One 1\nTwo 2\nThree 3" | perl -ne 'print if /(?m)^Two (\d+)$/'

But I got a result as expected when I executed the .pl file the same. Please find the file below.

#!/usr/bin/perl

$inputstring="One 1\nTwo 2\nThree 3";
if ( $inputstring =~ /^Two (\d+)$/m )
{
print "Matching\n";
}

Can you please tell why the perl one-line command has not given the output?

$ perldoc perlrun