正则表达式找到和替换视觉工作室2013-2015

时间:2016-05-19 05:11:08

标签: regex visual-studio replace

我需要替换ff,但是我必须保留内部内容,只用类A替换tagA元素。任何没有A类的TagA都应保持不变。

<tagA class="a">
**random chars and line breaks occurrences**
</tagA>

<tagA class="a">
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
</tagA>

<tagA> //this guy should be left untouched since he is not class A
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
</tagA>

应替换为

<newTag>
**retain inner content**
</newTag>

<newTag>
**retain inner content**
**retain inner content**
**retain inner content**
</newTag>

<tagA>//untouched
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
**random chars and line breaks occurrences**
</tagA>

2 个答案:

答案 0 :(得分:3)

搜索:

<\s*tagA\s+class\s*=\s*(["'])a\1\s*>((?:.|[\r\n])*?)<\s*/\s*tagA\s*>

替换为:

<newTag>$2</newTag>

替代简化搜索模式:
如果您确定间距和使用的引号始终相同,您也可以使用此搜索模式:

<tagA class="a">((?:.|[\r\n])*?)</tagA>

此模式基本上省略了对可选间距的所有检查,并且删除了在开始标记中匹配单引号和双引号的可能性。

替代替代方案:
如果您使用简化搜索模式,标记的内容将位于第一个捕获组中,因此我们也需要最低限度地更改替换模式:

<newTag>$1</newTag>

上面的表达式使用Visual Studio 2015进行了测试。

搜索模式说明:

<匹配字符&#34;&lt;&#34;从字面上
\s*匹配任何类型的空格(除了换行符)之外的任何数字(包括零) tagA匹配标记名称&#34; tagA&#34;从字面上
\s+匹配任何类型的空白字符(换行符除外)中的一个或多个 class匹配键名&#34; class&#34;从字面上
\s* 见上文
=匹配字符&#34; =&#34;从字面上
\s* 见上文
(["'])匹配双引号或单引号,并将其存储为第一个捕获组
a匹配类值&#34; a&#34;从字面上
\1匹配与第一个捕获组完全相同的字符(此处为双引号或单引号)
\s* 见上文
>匹配字符&#34;&gt;&#34;从字面上
(启动第二个捕获组 (?:启动非捕获组 .匹配除换行符之外的任何字符 |匹配左侧或右侧的模式(由封闭的非捕获组限制)
[\r\n]匹配回车符或换行符,它们在Windows上形成换行符 )关闭非捕获组 *?匹配令牌之前的最短可能数量(包括零)(非捕获组)
)关闭第二个捕获组 <匹配字符&#34;&lt;&#34;从字面上
\s* 见上文
/匹配字符&#34; /&#34;从字面上
\s* 见上文
tagA匹配标记名称&#34; tagA&#34;从字面上
\s* 见上文
>匹配字符&#34;&gt;&#34;字面意思

替换模式的说明:

<newTag>插入文字&#34;&lt; newTag&gt;&#34;从字面上
$2插入匹配的第二个捕获组的内容 </newTag>插入文字&#34;&lt; / newTag&gt;&#34;字面意思

答案 1 :(得分:-1)

我不使用VS,所以我对此并不是那么多,但你要做的是匹配以下模式:<tagA(.*?) class="a">(.*?)</tagA>

然后将其替换为: <newTag \1>\2</newTag>

由于我没有自己的VS,我无法测试正则表达式,但这个想法应该是明确的。