简单的 perl 正则表达式替换 [英] Simple perl regex replacement
问题描述
这是我的 perl 代码:
Here is my perl code:
my $var="[url=/jobs/]click here[/url]";
$var =~ /\[url=(.+?)\](.+?)\[\/url\]/<a href="\1" style="text-decoration:none;color:#336699">\2</a>/g
我对 perl 很陌生,所以我知道它不正确,但是我如何正确执行此 regex 替换
.
I'm very new to perl so i am aware that its incorrect but how do i perform this regex replacement
correctly.
最终结果是将 $var
转换为 点击这里
The end result would be a transformation of $var
to <a href="/jobs">click here</a>
推荐答案
所以,你知道的所有答案的替代形式是 s///
So, with all the answers you know the substitute form is s///
但是,对于这么大的东西,您应该将其分成几部分
以便于维护.并且还有助于摆脱
分隔符地狱的泥潭.
However, with something this big you should break it up into parts
to make it easier to maintain. And also helps to get out of the
quagmire of delimiter hell.
这使用了一个预编译的正则表达式和一个用 s///e
This uses a pre-compiled regex and a callback function invoked with s///e
use strict;
use warnings;
# Pre-compiled regex
my $rx = qr{\[url=(.+?)\](.+?)\[/url\]};
# Callback
sub MakeAnchor {
my ($href,$text) = @_;
return '<a href="' . $href . '" style="text-decoration:none;color:#336699">' . $text . '</a>';
}
my $input = '[url=/jobs/]click here[/url]';
$input =~ s/$rx/MakeAnchor($1,$2)/eg;
print $input;
出局
<a href="/jobs/" style="text-decoration:none;color:#336699">点击这里</a>
这篇关于简单的 perl 正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!