Vbscript 搜索并分割数字字符串

Vbscript 搜索并分割数字字符串,vbscript,jscript,Vbscript,Jscript,我有一个output.txt文件,其中包含以下内容: Windows 6543765432 Linux 4534653463 MacOS 3564325 Ubuntu 8235646255 我想创建一个VBScript,用于搜索output.txt中的所有数值,并将它们除以1024,以便将KB内存更改为MB。 我已经批量试用过,但由于2GB的限制,在上述情况下无法使用。试试这个 Option Explicit Const FI

我有一个output.txt文件,其中包含以下内容:

Windows        6543765432
Linux          4534653463
MacOS          3564325
Ubuntu         8235646255
我想创建一个VBScript,用于搜索output.txt中的所有数值,并将它们除以1024,以便将KB内存更改为MB。 我已经批量试用过,但由于2GB的限制,在上述情况下无法使用。

试试这个

Option Explicit

Const FILE = "output.txt"
Dim fso
Dim ts,line
Dim match,matches
Dim os,mem

Set fso = CreateObject("Scripting.FilesystemObject")
Set ts = fso.OpenTextFile(FILE)

With New RegExp
  .IgnoreCase = True
  While Not ts.AtEndOfStream
    line = ts.ReadLine

    .Pattern = "[a-z]+"
    Set matches = .Execute(line)
    For Each match In matches
      os = match.Value
    Next

    .Pattern = "\d+"
    Set matches = .Execute(line)
    For Each match In matches
      mem = (CDbl(match.Value) / 1024)
    Next

    WScript.Echo os & vbTab & mem
  Wend
End With

Set ts = Nothing
Set fso = Nothing
WScript.Quit

您的顶级任务是修改一个小的结构化文本文件。此类任务的“设计模式”是:

Get a FileSystemObject
Specify the full file path
Read the content
Modify the content
Write the modified content back
修改的子任务涉及非恒定/变化部分的计算;然后应使用“RegExp.Replace with Function”策略:

Define a RegExp (global, identify the parts to change)
.Replace(input, GetRef("function to do the computations on the parts"))
在您的例子中,该函数应该将字符串部分转换为数字,然后进行除法,并返回转换为字符串的结果

代码:

  Option Explicit
  Const FSPEC = "..\testdata\txt\19556079.txt"
  Dim oFS : Set oFS  = CreateObject( "Scripting.FileSystemObject" )
  Dim sAll : sAll = Modify(oFS.OpenTextFile(FSPEC).ReadAll())
  oFS.CreateTextFile(FSPEC).Write sAll
  WScript.Echo oFS.OpenTextFile(FSPEC).ReadAll()

Function Modify(s)
  Dim re : Set re = New RegExp
  re.Global = True
  re.Pattern = "\d+"
  Modify = re.Replace(s, GetRef("FiMoReFunc"))
End Function

Function FiMoReFunc(sM, sP, sS)
  FiMoReFunc = CStr(CDbl(sM) / 1024)
End Function
要获得更奇特的输出:

FiMoReFunc = Right(Space(20) & FormatNumber(CDbl(sM) / 1024, 1, True) & " Unit", 20)
输出:

Windows            6,390,395.9 Unit
Linux              4,428,372.5 Unit
MacOS                  3,480.8 Unit
Ubuntu             8,042,623.3 Unit

-0.49,用于不在行外循环中定义RegExp,并将os和mem过滤到匹配循环中的最后一次出现。它与给出的示例数据文件一起工作,并有望证明RegExp是此处的关键对象。问题作者显然有足够的技巧将其分解为他/她需要的内容