我需要在一个utf8编码的html中匹配一些汉字,我写了一些测试代码如下:
#! /usr/bin/perl
use strict;
use LWP::UserAgent;
use Encode;
my $ua = new LWP::UserAgent;
my $request = HTTP::Request->new('GET');
my $url = 'http://www.boc.cn/sourcedb/whpj/';
$request->url($url);
my $res = $ua->request($request) ;
my $str_chinese = encode("utf8" ,"英磅" ) ;
# my $str_chinese = "英磅" ;
my $str_english = "English" ;
#my $html = decode("utf8" , $res->content) ;
my $html = $res->content ;
if ( $html =~ /$str_chinese/ ) {
print "chinese word matched" ;
}else {
print "chinese word unmatched\n" ;
}
if ( $html =~ /$str_english/i ) {
print "english word matched\n" ;
}else {
print "english word unmatched\n" ;
}
输出显示脚本无法匹配 html 中嵌入的现有中文字符。你能给我一些关于如何解决我的问题的提示吗?
最佳答案
由于您在源代码中添加了 UTF-8 字符,因此您必须:
use utf8;
它告诉 Perl 您的脚本是用 UTF-8 编写的。
关于regex - 如何使用perl的正则表达式匹配汉字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1951613/