perl 跨行匹配 /s

多行匹配:

问题:

你希望使用正则表达式在一个字符串包含多行,但是指定的字符(任何字符串除了换行) 

^(字符串开始)  $(字符串结束) 对于你不能正常工作, 你可能发生如果你是读取多行记录 或者 一次一个文件

6.6.2. Solution
Use /m, /s, or both as pattern modifiers. /s allows . to match a newline (normally it doesn't). If the target string has more than one line in it, 

/foo.*bar/s could match a "foo" on one line and a "bar" on a following line. 

This doesn't affect dots in character classes like [#%.], since they are literal periods anyway.

使用/m ,/s  或者两者都是作为修饰符。 /s 允许.(点号) 匹配一个换行符(通常不行)



[oracle@oadb tmp]$ cat a1.pl 
my $a="abc
123efg";

if ($a =~ /abc
(.*?)efg/){print "111111111111$1==$1
"};
if ($a =~ /abc.(.*?)efg/){print "2222222222222$1==$1
"};
if ($a =~ /abc.(.*?)efg/s){print "333333333333$1==$1
"};

[oracle@oadb tmp]$ perl a1.pl
111111111111$1==123
333333333333$1==123

如果目标字符串有多于一行,

/foo.*bar/s 会匹配一个"foo" 在一行 一个"bar"在接下来一行  这个不影响点号 在字符串中像[#%.]

[oracle@oadb tmp]$ cat a2.pl 
my $b="foo
121212bar";
if ($b =~ /foo(.*?)bar/s){print "$1===$1
"};
[oracle@oadb tmp]$ perl a2.pl 
$1===
121212

此时匹配到了一个换行符


[oracle@oadb tmp]$ cat a2.pl 
my $b="foo
121212bar";
if ($b =~ /foo.(.*?)bar/s){print "$1===$1
"};
[oracle@oadb tmp]$ perl a2.pl
$1===121212



[oracle@oadb tmp]$ cat a2.pl 
my $b="foo
121212
bar";
if ($b =~ /foo.(.*?).bar/s){print "$1===$1
"};
[oracle@oadb tmp]$ perl a2.pl 
$1===121212
原文地址:https://www.cnblogs.com/hzcya1995/p/13349059.html