VBscript正则表达式替换 [英] VBscript regex replace

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

问题描述

我不知道为什么这仅适用于找到的最后一个实例,而不是我期望的所有实例.任何帮助表示赞赏.

I have no idea why this is only applying to the last instance found, not all of them as I would expect. Any help appreciated.

输入字符串:

<a href="http://www.scirra.com" target="_blank" rel="nofollow">http://www.scirra.com</a><br /><br />
<a href="http://www.scirra.com" target="_blank" rel="nofollow">http://www.scirra.com</a><br /><hr>

正则表达式:

'SEO scirra links
Dim regEx
Set regEx = New RegExp

' BB code urls
With regEx
    .Pattern = "<a href=\""http://www.scirra.com([^\]]+)\"" target=\""_blank\"" rel=\""nofollow\"">"
    .IgnoreCase = True
    .Global = True
    .MultiLine = True
End With
strMessage = regEx.Replace(strMessage, "<a href=""http://www.scirra.com$1"" target=""_blank"" title=""Some value insert here"">")

set regEx = nothing

输出:

<a href="http://www.scirra.com" target="_blank" rel="nofollow">http://www.scirra.com</a><br /><br />
<a href="http://www.scirra.com" target="_blank" title="Some value insert here">http://www.scirra.com</a><br /><hr>

谁能阐明为什么只将标题添加到最后找到的实例? (我已经测试了更多,总是只适用于最后一个)

Can anyone shed light on why it's only adding the title to the last found instance? (I've tested with more, always just applies to last one)

推荐答案

正因为如此,您的正则表达式中:

It is because of this in your regex:

...a.com-->([^\]]+)<--

您尝试一次或多次匹配输入中不是]的所有内容.而且由于您输入的内容中根本没有],因此它吞没了所有内容(是的,甚至是换行符),但为了满足您的正则表达式的其余部分,必须回溯,这意味着它回溯到了 last em> " target="_blank" ....的出现.

You try and match everything which is not a ], once or more, in your input. And since there are no ] at all in your input, it swallows everything (yes, even newlines), but has to backtrack in order to satisfy the rest of your regex, which means it backtracks to the last occurrence of " target="_blank" .....

如果要替换rel="nofollow"并允许http://www.scirra.com后面有任何路径,则可以改用以下正则表达式:

If you want to replace the rel="nofollow" and allow any path behind http://www.scirra.com, you can use this regex instead:

(<a href="http://www\.scirra\.com((/[^/"]+)*/?)" target="_blank" )rel="nofollow">

并替换为:

$1title="Some value insert here">

复制/粘贴您的当前代码:

Copy/pasting your current code:

Dim regEx
Set regEx = New RegExp

' BB code urls
With regEx
    .Pattern = "(<a href=""http://www\.scirra\.com((/[^""/]+)*/?)"" target=\""_blank\"" )rel=\""nofollow\"">"
    .IgnoreCase = True
    .Global = True
    .MultiLine = True
End With
strMessage = regEx.Replace(strMessage, "$1title=""Some value insert here"">")

但是请注意,这在替换的URL中有严格的限制.例如,目标内容是否有可能是其他内容或更多属性?

Note however that this is quite restrictive in the replaced URLs. For instance, is there the possibility that the target content be something else, or that there are more attributes?

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

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