【问题标题】:Add html to perl Regex将 html 添加到 perl 正则表达式
【发布时间】:2016-10-12 01:38:32
【问题描述】:

我正在尝试用 HTML 代码标记替换所有 ``

替换:

$string = "Foo `FooBar` Bar";

与:

$string = "Foo <code>FooBar</code> Bar";

我试过这些

$pattern = '`(.*?)`';

my $replace = "<code/>$&</code>";
$subject =~ s/$pattern/$replace/im;

#And

$subject =~ s/$pattern/<code/>$&</code>/im;

但它们都不起作用。

【问题讨论】:

  • 注意斜线。
  • 您的字符串在$string 中,但您在$subject 上执行s///。你能展示你的实际代码吗?你能说明什么不起作用吗?
  • 是 Markdown 吗?如果是这样,请查看Text::Markdown

标签: regex perl


【解决方案1】:

假设您的意思是 $string 而不是 $subject...

use strict;
use warnings;
use v5.10;

my $string = "Foo `FooBar` Bar";

my $pattern = '`(.*?)`';
my $replace = "<code/>$&</code>";

$string =~ s{$pattern}{$replace}im;
say $string;

这会导致...

$ perl ~/tmp/test.plx
Use of uninitialized value $& in concatenation (.) or string at /Users/schwern/tmp/test.plx line 9.
Foo <code/></code> Bar

这里有一些问题。首先,$&amp; 表示最后匹配的字符串。这就是`FooBar` 的全部内容。你只想要FooBar,它在捕获括号内。你可以通过$1 得到它。见Extracting Matches in the Perl Regex Tutorial

其次是$&amp;$1 是变量。如果你把它们放在像$replace = "&lt;code/&gt;$&amp;&lt;/code&gt;" 这样的双引号中,那么Perl 将立即 插入它们。这意味着$replace&lt;code/&gt;&lt;/code&gt;。这就是警告的来源。如果你想使用$1,它必须直接进入替换。

最后,在引用正则表达式时最好使用qr{}。那是特殊的正则表达式引用。它避免了各种引用问题。

把它们放在一起......

use strict;
use warnings;
use v5.10;

my $string = "Foo `FooBar` Bar";

my $pattern = qr{`(.*?)`};
$string =~ s{$pattern}{<code/>$1</code>}im;

say $string;

【讨论】:

  • 有没有其他方法可以使用$1而不用直接替换。喜欢制作类似$replace = '&lt;code&gt;$i&lt;/code&gt;'的东西
  • @ChrysUgwu 是的,但我不推荐它,因为这是一个安全漏洞。如果您使用s{}{}e,则右侧将被评估,就好像它是代码一样。但是现在你很容易受到代码注入的影响。它像插值一样工作。 my $foo = 23; my $bar = q[this $foo]; print "$bar" 会说 this $foo。但是如果你print eval qq["$bar"] 你得到this 23... 但$bar 可以包含任何代码。
  • 所以 Perl 不提供任何安全模式替换,如 php? php.net/manual/en/function.preg-replace.php
  • @ChrysUgwu 搜索和替换是安全的,除非你让它变得不安全。但它不支持在字符串中扩展$1,就像 PHP 在示例 #1 中所做的那样。可能有事要做,但我不知道。我建议将其作为一个新问题提出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2023-03-30
  • 2014-08-17
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多