我有一些正在处理的文件,我想从非日期字段中删除破折号。
我想到了 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/