Perl中的正则表达式替换包含双等号的内容

时间:2016-04-20 22:37:15

标签: regex perl

我需要在Perl中使用正则表达式来解决这个问题:

std::string

进入这个:

(== doc_url html/arbitrary_file_name.html ==)

我尝试过各种各样的事情。我目前的尝试看起来像这样:

(/doc_assets/legacy/html/arbitrary_file_name.html)

(在这个特殊的尝试中,我只是让括号括起来,因为它不会从输入变为输出。)

无论如何,没有什么对我有用。我认为它是$content =~ s!\=\= doc_url ([\w\W]+?)\=\=!/doc_assets/legacy/$1!gis; 扔掉的东西。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:-1)

我想你需要这样的东西:

s!.*?doc_url (.*?/.*?) .*!(/doc_assets/legacy/$1)!sg

<强>即:

#!/usr/bin/perl
$subject = "(== doc_url html/arbitrary_file_name.html ==)";
$subject =~ s!.*?doc_url (.*?/.*?) .*!(/doc_assets/legacy/$1)!sg;
print $subject;
#(/doc_assets/legacy/html/arbitrary_file_name.html)

Ideone Demo

正则表达式说明:

.*?doc_url (.*?/.*?) .*

Options: Case sensitive; Exact spacing; Dot matches line breaks; ^$ don’t match at line breaks; Numbered capture

Match any single character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “doc_url ” literally (case sensitive) «doc_url »
Match the regex below and capture its match into backreference number 1 «(.*?/.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match the character “/” literally «/»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “ ” literally « »
Match any single character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»

(/doc_assets/legacy/$1)

Insert the character string “(/doc_assets/legacy/” literally «(/doc_assets/legacy/»
Insert the text that was last matched by capturing group number 1 «$1»
Insert the character “)” literally «)»