gpt4 book ai didi

regex - VBscript 正则表达式替换

转载 作者:行者123 更新时间:2023-12-01 11:03:07 24 4
gpt4 key购买 nike

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

输入字符串:

<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>

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

最佳答案

这是因为在您的正则表达式中:

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

你尝试匹配所有不是 ] 的东西,一次或多次,在您的输入中。因为没有 ]在您的输入中,它吞没了所有内容(是的,甚至是换行符),但必须回溯以满足您的正则表达式的其余部分,这意味着它回溯到最后一次出现 " target="_blank" .... .

如果要更换 rel="nofollow"并允许后面的任何路径 http://www.scirra.com ,您可以改用此正则表达式:
(<a href="http://www\.scirra\.com((/[^/"]+)*/?)" target="_blank" )rel="nofollow">

并将其替换为:
$1title="Some value insert here">

复制/粘贴您当前的代码:
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 中非常严格。例如,目标内容是否有可能是别的东西,或者有更多的属性?

关于regex - VBscript 正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8859541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com