Home > other >  In perl match a dot when there're at least three words before it
In perl match a dot when there're at least three words before it

Time:09-24

I'm using (?<=(?:(?:\w|,|'){1,20} ){2}(?:\w|,|'){1,20} ?)\. But it's not working as expected:

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;

It should print out If you have to go and you go. That's no problem

Is there an easier way to achieve this?

CodePudding user response:

#!/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;

splits like you want. Using \K to discard everything before the period from the actual match is the key bit. (There's probably tweaks that could be made to the RE to better account for edge cases you didn't provide in your example string).

  • Related