regex - 如何使用perl的正则表达式匹配汉字

标签 regex perl

我需要在一个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/

相关文章:

perl - 在无限循环中杀死通过 system() 函数运行的子进程在 perl 中不起作用

perl - 使用 `bless` 创建具有继承的对象

python - 如何在 python 中通过\r\n 进行正则表达式

c# - 执行 Regex.Replace 时出现 "String too long for TextMeshGenerator. Cutting off characters."- Unity C#

regex - 如何连接行并添加分隔符?

perl - 在 Perl 中处理不同基数的命令行参数

c# - 正则表达式替换行首的任意数量的匹配项

C++ 正则表达式排除双引号不起作用

perl - Perl 中的 open 和 sysopen 有什么区别?

perl - 在 Perl 中,如何将多个类放入单个 .pm 文件中