首页 > 解决方案 > 在 perl 中,当它之前至少有三个单词时匹配一个点

问题描述

我正在使用(?<=(?:(?:\w|,|'){1,20} ){2}(?:\w|,|'){1,20} ?)\. 但它没有按预期工作:

use v5.35.2;
use warnings;
use strict;

my $str = shift // q{If you have to go. you go. That's no problem.}; 

my $regex = qr/(?<=(?:(?:\w|,|'){1,20} ){2}(?:\w|,|'){1,20} ?)\./;

my @all_parts = split $regex, $str;

say for@all_parts;

它应该打印出来If you have to go you go. That's no problem

有没有更简单的方法来实现这一点?

标签: regexperl

解决方案


#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;

my $str = shift // q{If you have to go. you go. That's no problem.}; 
my $regex = qr/(?:\b[\w,']+\s*){3}\K\./; 
my @all_parts = split $regex, $str;
say for @all_parts;

像你想要的那样分裂。使用\K在实际匹配期间丢弃所有内容是关键位。(可能会对 RE 进行一些调整,以更好地说明您在示例字符串中未提供的边缘情况)。


推荐阅读