正则表达式:在匹配项中搜索


Regex: Search within match

这是来源:

<item>
  <title>Quarterly Report ( Third Quarter 2013 )</title>
  <link>http://www.example.com/reports/Q3 2013_Final.pdf</link>
  <pubDate>24 Oct 2013 00:00:00 +0500</pubDate>
</item>

我需要将空格替换为 %20 ,仅在 URL 中。

我该怎么做?

编辑:源数据来自另一个我无法访问的网站,我不想仅仅为了替换空格字符而解析XML。

从您的评论中假设您正在使用 php。

这个呢

function FixSpace($match)
{
    $out  = $match[1];                          // opening tag
    $out .= str_replace(' ', "%20", $match[2]); // url
    $out .= $match[3];                          // closing tag
    return $out;
}
$input = preg_replace_callback("~(<link>)(.*?)(</link>)~", "FixSpace", $input);

首先使用正则表达式".*"选择链接标签和内容,然后将空格(即''s)替换为%20

我已经用红宝石语言写了例子。

str= "<item>

季度报告 ( 2013年第三季 ) http://www.example.com/reports/Q3 2013_Final.pdf 2013年10月24日 00:00:00 +0500'" str.scan(/.*/).first.gsub(/''s/,'%20')