程序员的知识教程库

网站首页 > 教程分享 正文

Perl 正则表达式的奇技淫巧1(perl语言正则表达式)

henian88 2024-10-10 05:51:34 教程分享 2 ℃ 0 评论

"\K" escape 来自于Regexp::Keep, 在perl5.10 版本中加入到变成perl 正则表达式的一部分:

通常用来处理正则表达式的性能问题, 意思是在正则表达式的匹配从\K之后的开始:

先上例子:

# slow and inefficient

my $r = "abc.def.ghi.jkl";

$r =~ s/(.*)\..*/$1/;

# fast and efficient

my $s = "abc.def.ghi.jkl";

$s =~ s/.*\K\..*//;

更多例子

:意思是所有被匹配的字符串, 可以看到下面的例子中一直在向后退,原因是\K位置的移动。

"alphabet" =~ /([^aeiou][a-z][aeiou])[a-z]/;

# $1 is "pha", is "phab"

"alphabet" =~ /\K([^aeiou][a-z][aeiou])[a-z]/;

# $1 is "pha", is "phab"

"alphabet" =~ /([^aeiou]\K[a-z][aeiou])[a-z]/;

# $1 is "pha", is "hab"

"alphabet" =~ /([^aeiou][a-z]\K[aeiou])[a-z]/;

# $1 is "pha", is "ab"

"alphabet" =~ /([^aeiou][a-z][aeiou])\K[a-z]/;

# $1 is "pha", is "b"

"alphabet" =~ /([^aeiou][a-z][aeiou])[a-z]\K/;

# $1 is "pha", is ""

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表