我有一个脚本采取mythtvlogging显示和编码在h264使用手刹。 该脚本是用Perl编写的。
我的问题是我如何replace空格和特殊字符与下划线使用Perl?
当输出"Parks and Recreation - S05E01 - Ms. Knope Goes to Washington"
时,string看起来像这样。
我希望看起来像这样
Parks_and_Recreation_S05E01_Ms__Knope_Goes_to_Washington
提前致谢。 我做了一些Googlesearch,但发现了一些有用的东西,我可以实现。
像这样的东西可能会做到这一点 – 注意,如果你像这样转换字符串,你可能会引入重复。
my $input ="Parks and Recreation - S05E01 - Ms. Knope Goes to Washington"; $input =~ s/ - /_/g; # Replace all " - " with "_" $input =~ s/[^A-Za-z0-9]/_/g; # Replace all non-alphanumericals with "_" print $input;
这输出:
Parks_and_Recreation_S05E01_Ms__Knope_Goes_to_Washington
编辑
下面的评论意见是非常相关的,这是一个稍微好一点的方法,在替换之前用不发音的重音字符替换:
use utf8; use Unicode::Normalize; my $input="La femme d'à côté"; my $result = NFD($input); # Unicode normalization Form D (NFD), canonical decomposition. $result !~ s/[^[:ascii:]]//g; # Remove all non-ascii. $result =~ s/ - /_/g; # Replace all " - " with "_" $result =~ s/[^A-Za-z0-9]/_/g; # Replace all non-alphanumericals with _ print $result;
这个变体输出:
La_femme_d_a_cote
my $input = "Parks and Recreation - S05E01 - Ms. Knope Goes to Washington"; $input =~ s/\W/_/g; # Replace anything other than letters, numbers and underscore
这输出:
Parks_and_Recreation___S05E01___Ms__Knope_Goes_to_Washington
你可以使用下面的:
perl -pe 's/[^A-Za-z0-9]/_/g'
测试:
> echo "Parks and Recreation - S05E01 - Ms. Knope Goes to Washington"|perl -pe 's/[^A-Za-z0-9]/_/g' Parks_and_Recreation___S05E01___Ms__Knope_Goes_to_Washington