使用替换变量搜索和替换正则表达式 [英] Search and replace with Regex with replace variables

查看:48
本文介绍了使用替换变量搜索和替换正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的公司在他们的移动网站上使用 3rd 方,我们有一个控制台来更新一些代码并通过它们控制东西.其中之一是可以更新站点代码的搜索和替换功能.唯一的一点是,它使用了很多复杂的正则表达式代码,我似乎找不到关于复杂内容的好教程.所以这是他给我的例子,sticks 抓取段落标签并将其放入链接中

So my company is using a 3rd party for their mobile sites and we have a console to update some of the code and control stuff through them. One of the things is a search and replace feature that can update the code for the site. The only this is, it uses a lot of complex regex code and I cant seem to find a good tutorial on the complex stuff. So here is the example he gave me that sticks grabs the paragraph tag and puts it in the link

搜索

(#d6d6d4.+?>.+?<p><a.+?>.+?)</a>(.+?)</td>

替换为

$1$2</a></td>

$1 和 $2 代表什么?我知道它可能与 .+ 之一有关?但我不确定是哪一个.如果有人知道请帮助我.我在正则表达式变量旁边添加了下面的代码

What is the $1 and $2 representing? I know it probably has something to do with one of the .+? but I am unsure which one. If anyone knows please help me. I have added the code down below with numbers next to the regex variables

(#d6d6d4.+?**[1]**>.+?**[2]**<p><a.+?**[3]**>.+?**[4]**)</a>(.+?**[5]**)</td>

推荐答案

$1 和 $2 表示正则表达式中捕获组中的文本.捕获组是括号内的内容.

The $1 and $2 represent the text in capturing groups in the regex. Capturing groups are what is inside parentheses.

 (        // start first capture group
 #d6d6d4  // match #d6d6d4
 .+?>     // any character, non-greedy, up to '>'
 .+?<p>   // any character, non-greedy, up to <p>
 <a.+?>   // an <a..> tag, consuming everything up to '>'
 .+?      // all characters from <a> to </a>
 )        // close the first capture group before the '</a>'
 </a>     // literal '</a>' 
 (        // start second capture group
 .+?      // match all, non-greedy up to '</td>'
 )        // close capture group before '</td>'
 </td>    // literal '</td>'

如果你有这个字符串:<td color=#d6d6d4 foo=bar>Hello, world<p><a href=http://foo.com>foo link</a>一些更多的文字

So you if you have this string: <td color=#d6d6d4 foo=bar>Hello, world<p><a href=http://foo.com>foo link</a>some more text</td>

$1 匹配:#d6d6d4 foo=bar>Hello, world

foo link$2 匹配:更多文本

$1 matches: #d6d6d4 foo=bar>Hello, world<p><a href=http://foo.com>foo link $2 matches: some more text

于是字符串转化为:<td color=#d6d6d4 foo=bar>你好,世界<p><a href=http://foo.com>foo linksome more text</a></td>

这基本上意味着 </a> 标签被移动到 some more text 之后(或者就在 </td> 之前)如果你愿意)

Which basically means the </a> tag is moved after some more text (or just before the </td> if you prefer)

这篇关于使用替换变量搜索和替换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆