【问题标题】:Perl split the string and print separator tooPerl 也拆分字符串和打印分隔符
【发布时间】:2020-04-01 10:14:09
【问题描述】:

我有一个字符串,并根据冒号(:) 或分号(;) 进行拆分,后跟空格。

这里是代码 sn-p。

my $string = "MAJOR RCB_Board: Circuit Disconnected";

my ($rest, $text) = split(/;|:\s+/, $string);
print "Rest=$rest ** Text=$text\n";

但在这里我也想用字符串打印分割分隔符。在此示例中 (:)。

所以我应该得到如下输出:

Rest=MAJOR RCB_Board: ** Text=Circuit Disconnected

【问题讨论】:

  • 您可以将正则表达式放在括号中以返回分隔符,请参阅the documentation
  • 另请注意\s+ 仅出现在右侧替代项中,您可能指的是/[;:]\s+/

标签: perl split


【解决方案1】:

您可以通过将分隔符放入括号中来捕获(部分)分隔符。

例如:

my $string = "MAJOR RCB_Board: Circuit Disconnected";

my ($rest, $separator, $text) = split(/(;|:)\s+/, $string);
print "Rest=$rest$separator ** Text=$text\n";

【讨论】:

  • my $string = "MAJOR RCB_Board: Circuit Disconnected: what"; 如果第三次分裂出现在: what,我们该怎么办?
  • 如果我们愿意,我们可以添加 ,2 作为拆分的第三个参数,因此 $text 将是 'Circuit Disconnected: what'。更多详情,您可以查找edoras.sdsu.edu/doc/perldoc-html/functions/split.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 2016-07-30
  • 2017-12-08
相关资源
最近更新 更多