用 Perl 匹配两个重叠模式 [英] Matching two overlapping patterns with Perl

查看:54
本文介绍了用 Perl 匹配两个重叠模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的问题没有被其他人提出,因为我试图查看网站上几乎所有地方,但我无法找到答案.

I hope that my question has not already been posed by someone else, since I tried to look almost everywhere in the site but I couldn't manage to find an answer.

我的问题是:我正在制作一个 PERL 脚本,它必须检测字符串中另一个模式的每次出现的位置.

My problem is: I'm making a PERL script which has to detect the position of every occurrence of one or another pattern in a string.

例如:

$string = "betaalphabetabeta";
$pattern = "beta|alpha";

在这种情况下,我希望我的脚本返回 4 个匹配项.

In this case, I would like my script to return 4 matches.

我认为这可以通过像这样使用匹配运算符来轻松实现:

I thought that this could be easily achieved by using the match operator in someway like this:

$string =~ /beta|alpha/g;

但是,由于我的两个模式(alpha"、beta")部分重叠,因此我刚刚发布的这段代码会在第一个模式与第二个模式重叠时跳过第一个模式的任何出现.

However, since my two patterns ("alpha", "beta") are partially overlapping, the piece of code that I've just posted skips any occurrence of the first pattern when it overlaps with the second one.

例如如果我有这样的字符串:

E.g. if I have a string like this one:

$string = "betalphabetabeta";

它只返回 3 个匹配项而不是 4 个.

it only returns 3 matches instead of 4.

我尝试用 ?= 运算符做一些事情,但我无法以正确的方式将它与 OR 运算符结合起来......

I've tried to do something with the ?= operator, but I can't manage to couple it with the OR operator in a correct way...

有没有人有解决办法?感谢您的帮助!

Does anyone have any solution? Thanks for your help!

推荐答案

以下使用零宽度断言(我相信这就是它的名字).

The following uses a zero-width assertion (I believe that's what it's called).

#!/usr/bin/perl
use strict;
use warnings;

$_ = "betalphabetabeta";

while (/(?=(alpha|beta))/g) {
    print $1, "\n"; 

打印:

C:\Old_Data\perlp>perl t9.pl
beta
alpha
beta
beta

这篇关于用 Perl 匹配两个重叠模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆