【问题标题】:'<' in Perl substitution REPLACE fieldPerl 替换 REPLACE 字段中的“<”
【发布时间】:2019-02-06 22:50:16
【问题描述】:

为什么要应用 perl 代码

 undef $/;  # read in entire file or STDIN
 $_ = <>;
 s|<head>.*<\head>|<head>...</head>|s;

应用于包含

的文本文件
 <head>[anything]</head>

生产

 ...

而不是

 <head>...</head>

?

当替换REPLACE字段中的'

 s|<head>.*</head>|head>.../head>|s;

替换产生

 head>...end>

如何在替换结果中产生一个'

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。您的原始代码中有一个错误,s|&lt;head&gt;.*&lt;\head&gt;|。注意\h 而不是/h\h 匹配“水平空白”。这是你的真实代码吗?还是你粘贴有误?否则s|&lt;head&gt;.*&lt;/head&gt;|&lt;head&gt;...&lt;/head&gt;|s; 很好,虽然you should not use regexes to parse HTML
  • 假设&lt;\head&gt; 是一个错误,您的代码会按照您的预期进行。无论您使用什么来查看结果,都可能是您缺少标签的原因。您在浏览器中查看输出吗?

标签: perl substitution


【解决方案1】:

第一个 sn-p 不会产生您声称的输出。

$ perl -e'$_ = "<head>foo</head>"; s|<head>.*<\head>|<head>...</head>|s; CORE::say'
<head>foo</head>

它不执行替换的原因是因为\h 匹配一个水平空白字符。

您可能打算使用&lt;/head&gt; 而不是&lt;\head&gt;。这会产生所需的输出。

$ perl -e'$_ = "<head>foo</head>"; s|<head>.*</head>|<head>...</head>|s; CORE::say'
<head>...</head>

正如您所声称的,即使与您的代码相似,也不会产生 ...。当然,如果您在 HTML 查看器中查看包含&lt;head&gt;...&lt;/head&gt; 的文件,它将显示为...。要生成呈现为 &lt;head&gt;...&lt;/head&gt; 的 HTML,您需要执行一些转义。

$ perl -e'
   use HTML::Escape qw( escape_html );
   $_ = "<head>foo</head>";
   s|<head>.*</head>|<head>...</head>|s;
   CORE::say(escape_html($_));
'
&lt;head&gt;...&lt;/head&gt;

【讨论】:

    【解决方案2】:

    假设&lt;\head&gt; 是一个错误,那么您的代码会按照您的预期进行。无论您使用什么来查看结果,都可能是您缺少标签的原因。您是在浏览器中查看输出吗?

    当您删除开头的&lt; 时,标签不再看起来像标签,而是显示而不是被操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2016-04-19
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      相关资源
      最近更新 更多