in reply to split string at variable position with matching
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: split string at variable position with matching
by AnomalousMonk (Archbishop) on Sep 12, 2021 at 02:28 UTC | |
|
Re^2: split string at variable position with matching
by LanX (Saint) on Sep 11, 2021 at 20:44 UTC | |
by choroba (Cardinal) on Sep 11, 2021 at 22:01 UTC |