perl拆分,但保留第二个字符串的特殊分隔符

时间:2018-12-18 16:59:54

标签: perl

下面有我需要拆分的以下字符串,但我需要将分隔符与字符串的第二部分保持在一起。这样我最终得到:

$a = 'State of mind is primary';
$b = '\098\455\098evertyhing else is secondary.-Eckhart Tolle '

我的尝试

my $string = 'State of mind is primary\098\455\098evertyhing else is secondary. -Eckhart Tolle';

my $separator = '\098\455\098';
my ($a, $b) = split($separator, $string);
print "$a\n";
print "$b\n";

如何通过perl split完成此操作?

3 个答案:

答案 0 :(得分:7)

分割在序列前面的0长度字符串上。

my ($x, $y) = split(/(?=\\098\\455\\098)/, $string);

答案 1 :(得分:2)

使用积极的前瞻方式。

(我已经简化了分隔符,以消除一个潜在的混乱来源)

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $string = 'State of mind is primaryXXXevertyhing else is secondary. -Eckhart Tolle';
my $separator = 'XXX';

my ($first, $second) = split /(?=$separator)/, $string;

say "$first / $second";

输出:

$ perl split
State of mind is primary / XXXevertyhing else is secondary. -Eckhart Tolle

答案 2 :(得分:0)

请勿使用split()使用模式匹配。

编辑,我想您的意思是\而不是八进制字符:

my $string = "State of mind is primary\\098\\455\\098\everything else is secondary. -Eckhart Tolle";
my($a, $b) = ($string =~ /^(.+)(\\098\\455\\098.+)$/);
print "A: '$a'\n";
print "B: '$b'\n";

输出:

A: 'State of mind is primary'
B: '\098\455\098ertyhing else is secondary. -Eckhart Tolle'