regex - perl正则表达式删除破折号

标签 regex perl

我有一些正在处理的文件,我想从非日期字段中删除破折号。

我想到了 s/([^0-9]+)-([^0-9]+)/$1 $2/g 但这只有在只有一个破折号的情况下才有效在字符串中,或​​者我应该说它只会删除一个破折号。

假设我有:

 2014-05-01
 this-and
 this-and-that
 this-and-that-and-that-too
 2015-01-01

我将使用什么正则表达式来生成

 2014-05-01
 this and
 this and that
 this and that and that too
 2015-01-01

最佳答案

不要只使用一个正则表达式。没有要求单个正则表达式必须包含所有代码逻辑。

使用一个正则表达式查看它是否是日期,然后使用第二个正则表达式进行转换。如果将它分成两部分,读者(将来就是你)会清楚得多。

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

while ( my $str = <DATA>) {
    chomp $str;
    my $old = $str;
    if ( $str !~ /^\d{4}-\d{2}-\d{2}$/ ) {  # First regex to see if it's a date
        $str =~ s/-/ /g;                    # Second regex to do the transformation
    }
    print "$old\n$str\n\n";
}
__DATA__
2014-05-01
this-and
this-and-that
this-and-that-and-that-too
2015-01-01

运行给你:

2014-05-01
2014-05-01

this-and
this and

this-and-that
this and that

this-and-that-and-that-too
this and that and that too

2015-01-01
2015-01-01

关于regex - perl正则表达式删除破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27826952/

相关文章:

php - 正则表达式允许字母数字和点

perl - 如何从 perl 连接到 gmail?

perl - 如何在不使用 eval 的情况下动态包含 Perl 模块?

Perl 用户输入

php - 正则表达式捕获 PHP SQL 字符串语句中插入的变量

python - find_all 没有在混合内容中找到文本

java - 正则表达式减少函数参数之间的空格

regex - 使用 REGEXP_EXTRACT 没有给出预期的结果 - Hive

Perl:如何使用 HTML::TableExtract 提取并组合表格的两个子部分?

perl - 定义的函数何时开始为未包含任何项目的数组返回 false