2

我有一个脚本,将 mythtv 录制的节目并使用手刹将它们编码为 h264。该脚本是用 Perl 编写的。

我的问题是如何使用 perl 用和下划线替换空格和特殊字符?

输出时字符串看起来像这样"Parks and Recreation - S05E01 - Ms. Knope Goes to Washington"

我希望它看起来像这样

Parks_and_Recreation_S05E01_Ms__Knope_Goes_to_Washington

提前致谢。我确实做了一些谷歌搜索,但发现了我可以实现的任何有用的东西。

4

3 回答 3

7

像这样的东西可能会这样做 - 请注意,如果您像这样转换字符串,您可能会引入重复项。

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

编辑

下面的Érics评论非常相关,这里有一个更好的方法,在进行替换之前用非重音符号替换重音字符:

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

于 2012-09-23T16:18:41.583 回答
2
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
于 2012-09-23T16:34:08.597 回答
-1

您可以使用以下内容:

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
于 2012-09-24T10:14:26.590 回答