Perl: Match multiple lines of text

Source: Internet
Author: User
Generally, regular expressions are for single-line text. Since Perl can process strings of any length, the Perl mode can easily match multiple lines of text, just like a single line of text. Of course, the expression should contain multiple lines of text. The following strings contain four rows:
$ _ = "I'm much better \ nthan Barney is \ Nat bowling, \ nwilma, \ n ";
Anchor ^ and $ indicate the start and end of the entire string, enhancing understanding. , ^And $ refer to the beginning and end of a string, not for a single row.However, the regular expression option/M allows them to match based on internal linefeeds (/M indicates multiple rows ). At this time, the anchor is targeted at each row, not the entire string. Therefore, this pattern can match:
Print "found 'wilm' at start of line \ n" if/^ Wilma \ B/IM;
Similarly, you can replace a single row in a multi-line string. In the following example, we read the entire file into a variable and add the file name to the beginning of each line:
Open File, $ filename
Or die "can't open '$ filename': $ !";
My $ lines = join '', <File>;
$ Lines = ~ S/^/$ filename:/GM;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.