regex - 使用散列的 Perl 替换

标签 regex perl

open (FH,"report");
read(FH,$text,-s "report");

$fill{"place"} = "Dhahran";
$fill{"wdesc:desc"} = "hot";
$fill{"dayno.days"} = 4;

$text =~ s/%(\w+)%/$fill{$1}/g;

print $text;

这是“报告”模板文件的内容

"I am giving a course this week in %place%. The weather is %wdesc:desc%
and we're now onto day no %dayno.days%. It's great group of blokes on the
course but the room is like the weather - %wdesc:desc% and it gets hard to
follow late in the day."

由于我不会深入探讨的原因,我将使用的散列中的一些键将包含点 (.) 或冒号 (:),但正则表达式对这些不起作用,例如在上面的示例中,只有 %place% 被正确替换。顺便说一下,我的代码是基于 this example .

非常感谢对正则表达式的任何帮助,或者可能有更好的方法...

最佳答案

您可以将其放宽并使用“不是 % 的任何序列”作为可替换标记:

$text =~ s/%([^%]+)%/$fill{$1}/g;

关于regex - 使用散列的 Perl 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969642/

相关文章:

php - 两个符号之间但不是该符号的三个之间的字符串的正则表达式

perl - 如何使用 perl 语言在 selenium 远程驱动程序中打开新选项卡并打开 url

Perltidy 始终按标准输出

perl - 为什么 "keys::"不是语法错误?

perl - 防止 "mux_client_request_session: read from master failed: Broken pipe"ssh 错误的最佳方法

perl - 如何让 Perl 运行我在 BASH 中定义的别名?

c - IP 的正则表达式 c 部分

Javascript正则表达式用新词替换多个词

Java正则表达式连接单个字母

java - 适用于不同语言环境的正则表达式