perl 跨行匹配;

本文介绍Perl中如何使用正则表达式进行跨行匹配。通过使用/m和/s修饰符,可以让特定的元字符识别换行符,实现多行记录的匹配。示例代码演示了如何匹配两行之间的文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="html"><pre name="code" class="html">perl  跨行匹配;
6.6. Matching Within Multiple Lines
6.6.1. Problem
You want to use regular expressions on a string containing more than one logical line, but the special characters . (any character but newline), ^ (start of string), and $ (end of string) don't 

seem to work for you. This might happen if you're reading in multiline records or the whole file at once. 

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.

The /m modifier allows ^ and $ to match immediately before and after an embedded newline, respectively. /^=head[1-7]/m would match that pattern not just at the beginning of the record, but anywhere 

right after a newline as well.


多行匹配

6.6.1 问题


你需要使用正则表达式在一个自付出啊吧 包含多个逻辑行, 但是特定的字符串(任何字符串除了换行) 

^ 表示字符串开始

$ 字符串结束 似乎不能为你工作 。

这个可能发生如果你读取多行 记录 


6.6.2 解决

使用/m ,/s  或者两者  作为模式修改 

/s 允许. 匹配一个换行(通常它不能)  如果目标字符串有多余一行,

/foo,*bar/s  可以匹配一个"foo 在一行和一个"bar" 在另外一行  这个不会影响点号 在字符类 
the "." metacharacter matches any character except
    "\n" (unless you use "/s")



/m 修饰符 允许 ^和$来立即匹配 之前和之后一个嵌入的换行符,分别的,


/^=head[1-7]/m

会匹配 模式不是在记录的开始,但是任何右边在一个新行




/s 当作一行处理

/s 令 . 匹配换行符并且忽略不建议使用的 $* 变量

/m 令 ^ 和 $ 匹配下一个嵌入的 \n。


zjtest7-frontend:/root# cat a2.pl 
my $str="sdgs
sdgdsg
begin
ddd
...
end 
d,,,,
sdsdg
begin 
sdsg
end ";
if ($str =~/.*?begin.(.*).end/s){
    print "\$1 is $1\n";
   };
   


zjtest7-frontend:/root# perl a2.pl 
$1 is ddd
...
end 
d,,,,
sdsdg
begin 
sdsg


The /m modifier allows ^ and $ to match immediately before and after an embedded newline, respectively. /^=head[1-7]/m would match that pattern not just at the beginning of the record, but anywhere right after a newline as well.




   

转载于:https://www.cnblogs.com/zhaoyangjian724/p/6199383.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值