【发布时间】:2014-12-05 15:22:39
【问题描述】:
我正在尝试获取目录中的所有文件名并确定哪些名称包含特殊字符。我正在使用正则表达式
/[^-a-zA-Z0-9_.]/
示例文件(我使用触摸创建):
pdf-2014à014&7_06_64-Os_O&L,_Inc.pdf
pdf-20_06_04-O_OnLine,_Inc.pdf
pdf-20_0_0-Utà_d.wr.pdf
pdf-20_12_28-20.Mga_Grf.Fwd_Notice_KDJFI789&_JFK38.pdf
pdf-2_0_0-C_—_DUKE.pdf
pdf-2_1_3-f_s-M_F_D&A.pdf
pdf_-_2014à014&1007_0617_06264-O_O&L,_Inc.pdf
在我匹配正则表达式中的模式名称之前,Perl 可以输出正确的名称一次。是的 perl 能够以某种方式匹配特殊字符,但是在输出字符时会发生变化。
* pdf-2_0_0-C_—_DUKE.pdf > pdf-2_0_0-C_???_DUKE.pdf
我可以尝试取消注释这一行
#binmode(STDOUT, ":utf8");
然后再次运行命令脚本。确定?标记将被删除,但输出也不同。
* pdf-2_0_0-C_—_DUKE.pdf > pdf-2_0_0-C_â_DUKE.pdf
这是我的代码:
use strict;
use warnings;
use File::Find;
use Cwd;
#binmode(STDOUT, ":utf8");
my $starting_directory = cwd();
use Term::ANSIColor;
checkForSpecialChar(cwd());
sub checkForSpecialChar{
my ($source_dir) = @_;
chdir $source_dir or die qq(Cannot change into "$source_dir");
find ( sub {
return unless -f; #We want files only
print "\n";
while(m/([^-a-zA-Z0-9_.])/g){
chomp($_);
print "DETECTED: |" . $_ . "|\n";
print $`;
print color 'bold red';
print "$1";
print color 'reset';
print $' . "\n";
}
}, ".");
chdir("$starting_directory");
有什么想法吗?
更新: 嗯,你们是对的,看起来它不是正则表达式的问题。嗨 AKHolland,我尝试将代码更改为与您的测试相同。但仍然会产生与 hypen 和小写字母 a-grave 相同的问题。 而不是一个小写字母a-grave它给了我 a` 当不使用 binmode(STDOUT, ":utf8"); aÌ 当使用 binmode(STDOUT, ":utf8");
use strict;
use warnings;
use File::Find;
use Cwd;
use Encode;
binmode(STDOUT, ":utf8");
my $starting_directory = cwd();
use Term::ANSIColor;
checkForSpecialChar(cwd());
sub checkForSpecialChar{
my ($source_dir) = @_;
chdir $source_dir
or die qq(Cannot change into "$source_dir");
find ( sub {
return unless -f; #We want files only
print $_ . "\n";
$_ = Encode::decode_utf8($_);
for(my $counter =0; $counter < length($_); $counter++) {
print Encode::encode_utf8(substr($_,$counter,1)) . "\n";
}
}, ".");
chdir("$starting_directory"); }
输出与 binmode(标准输出,“:utf8”); pdf-2_0_0-C_â_DUKE.pdf p d F - 2 _ 0 _ 0 - C _ 一种 _ D ü ķ 乙 . p d F pdf_-_2014aÌ014&1007_0617_06264-O_O&L,_Inc.pdf p d F _ - _ 2 0 1 4 一种 一世 0 1 4 & 1 0 0 7 _ 0 6 1 7 _ 0 6 2 6 4 - ○ _ ○ & 大号 , _ 一世 n C . p d F 无输出 binmode(标准输出,“:utf8”); pdf-2_0_0-C_—_DUKE.pdf p d F - 2 _ 0 _ 0 - C _ — _ D ü ķ 乙 . p d F pdf_-_2014à014&1007_0617_06264-O_O&L,_Inc.pdf p d F _ - _ 2 0 1 4 一种 ̀ 0 1 4 & 1 0 0 7 _ 0 6 1 7 _ 0 6 2 6 4 - ○ _ ○ & 大号 , _ 一世 n C . p d F【问题讨论】:
-
你的环境是什么? This version 您的代码在 OSX 输出上正确运行。
-
嗨米勒,我正在使用 Mac OSX 运行上面的代码。 Bash 能够正确输出它。如果我使用来自 find 的 'print $_',Perl 能够正确打印字符,但是在我将字符串传递给 substr 函数或正则表达式之后,返回字符串已经不同
-
大家好,我看到了类似的帖子perlmonks.org/bare/?node_id=316862。其中 substr 无法处理 utf8。我认为它与我的问题有一些关系,因为我尝试从它们输出这些文件名,直到我将它们传递给函数。如果我找到解决此问题的方法,我会发布
标签: regex perl unicode character