如何使用 RegEx 进行 2 次查找但仅进行 1 次替换?

How can I use RegEx to do 2 finds but only 1 replace?

编辑:我现在正在使用 PCRE RegEx 语言。

我有一个场景,我的网站上每个网页的顶部都有 VBScript 字符串值。 (该站点正在进行重新设计。)我需要在搜索和替换场景中使用这些分配,使用 RegEx,并替换 HTML 元素的另一部分以为其提供该字符串值。

下面的代码成功地从页面顶部的变量中提取了 "Member Access",我可以使用 $1 将该变量放置在某处。但这就是我卡住的地方。我需要将该值粘贴到其他地方,例如标签中。我应该在替换字段中输入什么来保留所有内容,但只替换某些项目,例如标题标签之间的文本?

我基本上需要找到两件事。找到第一个,然后在第二个找到时使用替换:
<title>this text</title>

 RegEx filter: /PageTitle = "(.*)"/ gm
 Replacement string: <everything before Page Title string>PageTitle = ""<everything after PageTitle string><title></title><Rest of content after title tag>

以下是我网站上每个页面的示例:

<% 
Page Title = "Member Access"
MetaDescription = "This is a paragraph describing our website that we use to place into the meta description tag in the head. This will give information about our site."
Keywords = "Awesome, Cool, Rad, Tubular"
%>

<!doctype HTML>
<html dir="ltr" lang="en">
<head>
<meta charset="UTF-8">

<!-- Meta Tags -->
<meta name="description" content="This needs to be replaced with MetaDescription variable at top of page">
<meta name="keywords" content= "these, need, to, be, gone">
<meta name="viewport" content="width=device-width, initial-scale=1.0 shrink-to-fit=no">


<!-- Twitter and Facebook Social media tags -->
<meta property="fb:app_id" content="" />
<meta property="og:title" content="This needs to be replace with Page Title variable at top of page" >
<meta property="og:description" content="This needs to be replaced with MetaDescription variable at top of page">

 <!-- Page Title -->
 <title>This needs to be replaced with Page Title variable at top of page</title>


 </head>

 <body>

 <div id="main" class="main-content">
 <section class="inner-header divider layer-overlay overlay-dark-4" data-bg-img="/images/_interior-banners/THIS NEEDS TO BE REPLACED CONDITIONALLY BASED ON SITE FOLDER" style="background-image: url('/images/_interior-banners/THIS NEEDS TO BE REPLACED CONDITIONALLY BASED ON SITE FOLDER'); ">

 <h1 id="page-title" class="font-36">This needs to be replaced by Page Title variable at top of page</h1>

 rest of webpage content......
 </div>
 </section>
 </body>
 </html>

好的...您需要匹配其中的多个位 - 然后将大部分位替换为原始位,仅将一些位替换为 "title" 匹配组

这是有效的正则表达式(在 Notepad++ 中,“. 匹配换行符”打开)

(Page Title = "([^"]*)")(.*)(<title>)([^<]*)(</title>)(.*)(<h1 id="page-title" class="font-36">)([^<]*)(</h1>)

因此给出了组:

 (Page Title = "([^"]*)") - The first bit  
 ([^"]*) - INSIDE  - the thing we are wanting to use as replacements elsewhere  
 (.*) - everything up until....   
 (<title>)  
 ([^<]*) - inside the title tag (ie we want to replace this)  
 (</title>) - title closing tag  
 (.*) - everything up until...  
 (<h1 id="page-title" class="font-36">) - h1 opening tag  
 ([^<]*) - inside the h1 tag (ie we want to replace this)  
 (</h1>)

注意否定字符组的使用 - 因此 </code> 匹配组表示任意数量的非 <code>" 字符 这很重要,因为正则表达式是贪婪的(我们希望在为该组命中 " 时停止,并移至下一组)

所以我们的替代品是...