无为清净楼资源网 Design By www.qnjia.com
首字母大小写无关模式
有一段时间,我在写正则表达式来匹配Drug关键字时,经常写出 /viagra|cialis|anti-ed/ 这样的表达式。为了让它更美观,我会给关键词排序;为了提升速度,我会使用 /[Vv]iagra/ 而非/viagra/i ,只让必要的部分进行大小写通配模式。确切地说,我是需要对每个单词的首字母进行大小写无关的匹配。

我写了这样的一个函数,专门用来批量转换。

复制代码 代码如下:
#convert regex to sorted list, then provide both lower/upper case for the first letter of each word
#luf means lower upper first

sub luf{
# split the regex with the delimiter |
my @arr=sort(split(/\|/,shift));

# provide both the upper and lower case for the
# first leffer of each word
foreach (@arr){s/\b([a-zA-Z])/[\l$1\u$1]/g;}

# join the keyword to a regex again
join('|',@arr);
}

print luf "sex pill|viagra|cialis|anti-ed";
# the output is:[aA]nti-[eE]d|[cC]ialis|[sS]ex [pP]ill|[vV]iagra

控制全局匹配下次开始的位置

记得jyf曾经问过我,如何控制匹配开始的位置。嗯,现在我可以回答这个问题了。Perl 提供了 pos 函数,可以在 /g 全局匹配中调整下次匹配开始的位置。举例如下:
复制代码 代码如下:
$_="abcdefg";
while(/../g)
{
print $&;
}

其输出结果是每两个字母,即ab, cd, ef

可以使用 pos($_)来重新定位下一次匹配开始的位置,如:

复制代码 代码如下:
$_="abcdefg";
while(/../g)
{
pos($_)--; #pos($_)++;
print $&;
}

输出结果:

复制代码 代码如下:
pos($_)--: ab, bc, cd, de, ef, fg.
pos($_)++: ab, de.

可以阅读 Perl 文档中关于 pos的章节获取详细信息。

散列与正则表达式替换
《effective-perl-2e》第三章有这样一个例子(见下面的代码),将特殊符号转义。
复制代码 代码如下:
my %ent = { '&' => 'amp', '<' => 'lt', '>' => 'gt' };
$html =~ s/([&<>])/&$ent{$1};/g;

这个例子非常非常巧妙。它灵活地运用了散列这种数据结构,将待替换的部分作为 key ,将与其对应的替换内容作为 value 。这样只要有匹配就会捕获,然后将捕获的部分作为 key ,反查到 value 并运用到替换中,体现了高级语言的效率。

不过,这样的 Perl 代码,能否移植到 Python 中呢? Python 同样支持正则,支持散列(Python 中叫做 Dictionary),但是似乎不支持在替换过程中插入太多花哨的东西(替换行内变量内插)。

查阅 Python 的文档,(在 shell 下 执行 python ,然后 import re,然后 help(re)),:

复制代码 代码如下:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used.

原来 python 和 php 一样,是支持在替换的过程中使用 callable 回调函数的。该函数的默认参数是一个匹配对象变量。这样一来,问题就简单了:

复制代码 代码如下:
ent={'<':"lt",
'>':"gt",
'&':"amp",
}

def rep(mo):
return ent[mo.group(1)]

html=re.sub(r"([&<>])",rep, html)

python 替换函数 callback 的关键点在于其参数是一个匹配对象变量。只要明白了这一点,查一下手册,看看该种对象都有哪些属性,一一拿来使用,就能写出灵活高效的 python 正则替换代码。
标签:
正则表达式,笔记

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。