regex - 在未找到 BGInfo 文件中使用 VBScript 时出错
问题描述
我是一个业余的 VB 脚本编写者。
我正在创建一个脚本来输出 ID。该文件包含“ad.annnet.id = 564654068”行。需要输出“ID:564654068”
With New RegExp
.Pattern = "\nID=(\d+)"
Echo .Execute(CreateObject("Scripting.FileSystemObject").OpenTextFile("this.conf").ReadAll)(0).Submatches(0)
End With
解决方案
脚本存在多个问题,“找不到文件”错误的实际原因是@craig在他们的回答中指出FileSystemObject
找不到文件“this.conf”。这是因为该OpenTextFile()
方法不支持相对路径,并且需要文件的绝对路径,无论它是否与正在执行的脚本位于同一目录中。
您可以通过调用GetAbsolutePathName()
并传入文件名来解决此问题。
来自官方文档 - GetAbsolutePathName 方法
假设当前目录是 c:\mydocuments\reports,下表说明了该
GetAbsolutePathName
方法的行为。
路径规范 (JScript) 路径规范 (VBScript) 返回路径 “C:” “C:” “c:\我的文档\报告” “C:..” “C:..” “c:\我的文档” “C:\” “C:” “C:” “c: . \may97” “c: . \may97” "c:\mydocuments\reports*.*\may97" “区域 1” “区域 1” "c:\mydocuments\reports\region1" "c:\..\..\mydocuments" “c:....\我的文档” “c:\我的文档”
像这样的东西应该有效;
'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = "this.conf"
Dim filepath: filepath = fso.GetAbsolutePathName(filename)
Dim filecontent: filecontent = fso.OpenTextFile(filepath).ReadAll
更新:看来您毕竟可以使用路径修饰符OpenTextFile()
(谢谢@LesFerch),所以这也应该有效;
'Read the file from the current directory (can be different from the directory executing the script, check the execution).
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim filename: filename = ".\this.conf" '.\ denotes the current directory
Dim filecontent: filecontent = fso.OpenTextFile(filename).ReadAll
另一个问题是当前RegExp
模式与您的期望不匹配,建议您先使用正则表达式 101之类的东西来测试您的正则表达式。
推荐阅读
- python - Draw dots based on (x,y) locations
- python - 龟扣的制作方法
- r - 在分级颜色/填充比例中指定分级颜色
- html - 从移动视图切换到平板视图时如何将 jQuery 移动侧面板从推送更改为覆盖
- clearcase - 有没有其他方法可以在 OMAKE 中格式化我的 %echo 输出(而不是使用 cygwin printf.exe,而是使用 OMAKE 它自己的任何本地化语法)
- r - 如何在 R 中使用 draw.pairwise.venn 更改维恩图的背景颜色?
- node.js - 从异步钩子 HTTPINCOMINGMESSAGE 获取 HTTP 标头/正文
- python - HDBSCAN 近似预测总是返回 0 的概率
- kubernetes - 用于获取 Kubernetes 集群的不记名令牌的 Rest 端点
- java - 简易巴士预约席