gpt4 book ai didi

regex - 无法在 vba IE 中应用正则表达式

转载 作者:行者123 更新时间:2023-12-01 09:36:28 25 4
gpt4 key购买 nike

我使用 vba 结合 IE 编写了一个脚本来解析来自应用 的网页的联系信息。正则表达式 在上面。我搜索了很多,但找不到任何可以满足我要求的示例。 pattern找到 phone 可能并不理想数字,但这里主要关心的是如何使用 pattern在 vba IE 中。

再说一遍:我的意图是解析电话号码 661-421-5861从那个网页申请 regex在 vba IE 中。

这是我迄今为止尝试过的:

Sub FetchItems()
Const URL$ = "https://www.nafe.com/bakersfield-nafe-network"
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim rxp As New RegExp, email As Object, Row&

With IE
.Visible = True
.navigate URL
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set HTML = .document
End With

With rxp
.Pattern = "(?<=Phone:)\s*?.*?([^\s]+)"
Set email = .Execute(HTML.body.innerText) 'I'm getting here an error
If email.Count > 0 Then
Row = Row + 1: Cells(Row, 1) = email.Item(0)
End If
End With
IE.Quit
End Sub

当我执行上述脚本时,我遇到了一个错误 对象“IRegExp2”的方法“执行”失败 当它到达包含 Set email = .Execute(HTML.body.innerText) 的行时.我怎样才能让它成功?

最佳答案

请注意,VBA 正则表达式不支持lookbehinds。在这里,您可能想要捕获 Phone: 之后的任意数字和任意数量的数字和连字符。 .

您需要将模式重新定义为

rxp.Pattern = "Phone:\s*(\d[-\d]+)"

然后,您需要获取第一场比赛并访问其 .SubMatches(0) :
Set email = .Execute(HTML.body.innerText)
If email.Count > 0 Then
Cells(Row+1, 1) = email.Item(0).SubMatches(0)
End If

regex in action .刺痛的绿色突出部分是 .SubMatches(0)持有。

图案详情
  • Phone: - 文字子串
  • \s* - 0+ 个空格
  • (\d[-\d]+) - 捕获组 1:一个数字,后跟 1+(由于 +,您可以替换为 * 以匹配零个或多个)数字或/和连字符。
  • 关于regex - 无法在 vba IE 中应用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303004/

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