【问题标题】:How to capture string before the symbol如何在符号之前捕获字符串
【发布时间】:2018-03-05 21:51:15
【问题描述】:

大家早上好, 我想在冒号之前捕获字符串: 然后比较冒号后面的字符串 并删除与冒号前值相等的值。

例如:

aaa:aaa-bbb-ccc

输出:

aaa others:bbb,ccc

下面是我的代码

$string = "aaa:aaa-bbb-ccc";
$first =~ /(:.*\)/; //get aaa before the colon
$others =$string=~ s/$first//; remove the same values after colon

你能帮帮我吗?谢谢。。

【问题讨论】:

  • (:.*\) 表示之后而不是之前。请澄清你的问题。既然你有两个aaa;这有点令人困惑。而且您的输出与您的模式非常不同。

标签: regex perl


【解决方案1】:

这行得通:

use strict;
use warnings;

my $s='aaa:aaa-bbb-ccc';
if ($s=~/^([^:]+):/) {
    my $first=$1;
    $s=~s/\Q$1\E://;
    print "$first others:" . join ',', grep { $_ ne $first } split '-', $s;
}
# aaa others:bbb,ccc

【讨论】:

  • ($s=~/^([^:]+):/) 这是访问冒号前的字符串
  • @Azhar:是的。它捕获字符串中第一个冒号左侧的所有字符。
猜你喜欢
  • 2014-09-19
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2019-06-16
  • 2018-09-04
  • 2019-06-24
相关资源
最近更新 更多