繁体   English   中英

Perl:如何使用起始字符拉出所需的字符串,但也需要包含它们?

[英]Perl: How to pull out the desired string using the starting character but needs to include them as well?

我有这个字符串

my $word = "Chase_^%798(987%55,.#*&^*&Chase_$&^**&(()%%hjjlhh";

期望的输出是

Chase_^%798(987%55,.#*&^*&
Chase_$&^**&(()%%hjjlhh

字符串"Chase_"是我应该将它们分开的唯一线索。 使用split我失去了字符串"Chase_" 然后我应该连接它们。 我对如何分割它没有任何想法,但也应该出现字符串"Chase_"

使用前瞻

my $str = 'Chase_^%798(987%55,.#*&^*&Chase_$&^**&(()%%hjjlhh';
my @list = split(/(?=Chase_)/, $str);
say Dumper\@list;

输出:

$VAR1 = [
          'Chase_^%798(987%55,.#*&^*&',
          'Chase_$&^**&(()%%hjjlhh'
        ];

如果你使用split的正则表达式进行分组,你就不会丢失(单个“o”)它。 此外,如果您拆分字符串文字而不是模式,则无需提取它:

#! /usr/bin/perl
use warnings;
use strict;

my $word = 'Chase_^%798(987%55,.#*&^*&Chase_$&^**&(()%%hjjlhh';

my @parts1 = split /(Chase_)/, $word;
for (my $i = 1; $i < $#parts1; $i += 2) {
    print @parts1[ $i, $i + 1 ], "\n";
}

print "--------\n";

my @parts2 = split /Chase_/, $word;
print 'Chase_', $_, "\n" for @parts2[ 1 .. $#parts2 ];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM