You can use the look-behind (?<= to specify that the space is preceded by that many characters:
#!/usr/bin/perl use strict; use warnings; my $string = "hello my * name is Rob * and * I am a very nice person * + at least * I think * so"; my $part1 = "hello my * name is Rob * and *"; my $part2 = "I am a very nice person * at least * I think * so"; sub split_before { my ($string, $pos) = @_; my $pos = rindex $string, '*', 30; split /(?<=^.{$pos}\*) /, $string, 2 } use Test2::V0; is "$part1 $part2", $string; is [split_before($string, 30)], [$part1, $part2]; done_testing();
BTW,
passes the first test, too (but not the second one, as the space is still part of $part1).(split /(^.{,30}\* )/, $string, 2)[1, 2]
Update: Read below for a fix, thanks AnomalousMonk. I shouldn't work on two different tasks at the same time.
In reply to Re: split string at variable position with matching
by choroba
in thread split string at variable position with matching
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |