簡體   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