不知者黑 2018-07-14 11:52 采纳率: 100%
浏览 1244
已采纳

VBS批量替换(转换)文本文件中的单位(求达人瞧一下)

需求:遍历文本文件,在里面找到像素单位(例:“100px”),替换成相对单位(例如:“3rem”);px与rem单位转换过程中是一个固定比例。

研究半天弄了下面一个脚本,但是不能替换到位。望大佬给个意见

 Dim regEx,Match,Matches
Set regEx = New RegExp    '创建一个正则表达式
regEx.Pattern = "^[1-9]\d*px$"     '设置正则表达式的匹配模式
regEx.IgnoreCase  = True  '设置为不区分大小写
regEx.Global  = True      '设置为全局可用

dim fso, f
set fso = CreateObject("Scripting.FileSystemObject")
set f = fso.OpenTextFile("1.txt", 1, false) '第二个参数 1 表示只读打开,第三个参数表示目标文件不存在时是否创建
set e = fso.OpenTextFile("2.txt", 8, True) 
Do Until f.AtEndOfStream
    strLine = f.ReadLine() '从当前位置向后读取直到遇到换行符(不读取换行符),并将当前位置移动到下一行的第一个字符,注意:无参数
     Set Matches = regEx.Execute(strLine)  '执行搜索
     For  Each  Match  in  Matches  '遍历所有的匹配
      x=Len(Match)
      n=Left(Match,x-2)                ' 拆分去掉最后的px
      o = n/30                            ' 换算。
      p ="rem"
      replStr = o&p' 拼接。
      MsgBox regEx.Peplace(strLine,replStr)
     Next
     e.WriteLine(strLine)
Loop

f.Close()
e.Close()
set f = nothing
set fso = nothing


  • 写回答

3条回答

  • weixin_42695878 2018-07-17 16:06
    关注
     Dim regEx,Match,Matches
    Set regEx = New RegExp    '创建一个正则表达式
    regEx.Pattern = "([1-9]\d*)px"     '设置正则表达式的匹配模式
    regEx.IgnoreCase  = True  '设置为不区分大小写
    regEx.Global  = True      '设置为全局可用
    
    dim fso, f
    set fso = CreateObject("Scripting.FileSystemObject")
    set f = fso.OpenTextFile("1.txt", 1, false) '第二个参数 1 表示只读打开,第三个参数表示目标文件不存在时是否创建
    set e = fso.OpenTextFile("2.txt", 8, True) 
    
    dim strLine
    Do Until f.AtEndOfStream
        strLine = f.ReadLine() '从当前位置向后读取直到遇到换行符(不读取换行符),并将当前位置移动到下一行的第一个字符,注意:无参数
        strResult = ""
        nextIndex = 1
        For Each m In regEx.Execute(strLine)
            strResult = strResult & Mid(strLine, nextIndex, m.FirstIndex - nextIndex + 1)
            strResult = strResult & CStr(round(CInt(m.Submatches(0))/ 30, 2))
            strResult = strResult & "rem"
            nextIndex = m.FirstIndex + Len(m.Value) + 1
        Next
    
        strResult = strResult & Mid(strLine, nextIndex)
        e.WriteLine(strResult)
    Loop
    
    f.Close()
    e.Close()
    set f = nothing
    set fso = nothing
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误