【问题标题】:Trim leading spaces including tabs修剪前导空格,包括制表符
【发布时间】:2010-11-09 01:48:18
【问题描述】:

我需要使用 vbscript 读取文件并删除所有前导空格,包括任何制表符。 我现在 LTRIM 将删除前导空格,但我如何也删除制表符。

谢谢。

【问题讨论】:

    标签: vbscript spaces trim


    【解决方案1】:

    此函数从字符串中删除所有前导空格(空格、制表符等):

    Function LTrimEx(str)
      Dim re
      Set re = New RegExp
      re.Pattern = "^\s*"
      re.Multiline = False
      LTrimEx = re.Replace(str, "")
    End Function
    

    【讨论】:

      【解决方案2】:

      对于多行字符串中的左右修剪(包括制表符、回车、换行、空格),这将起作用。

      Function MultilineTrim (Byval TextData)
          Dim textRegExp
          Set textRegExp = new regexp
          textRegExp.Pattern = "\s{0,}(\S{1}[\s,\S]*\S{1})\s{0,}"
          textRegExp.Global = False
          textRegExp.IgnoreCase = True
          textRegExp.Multiline = True
      
          If textRegExp.Test (TextData) Then
              MultilineTrim = textRegExp.Replace (TextData, "$1")
          Else
              MultilineTrim = ""
          End If
      End Function
      

      【讨论】:

        【解决方案3】:

        安德鲁的回答不正确。 LTrim、RTrim 和 Trim 只删除空格,而不是制表符。

        我重新格式化了您的代码,并添加了一个函数来去除任何前导或尾随字符。

        filename="test.txt"
        
        set fso = createobject("scripting.filesystemobject")
        set f = fso.opentextfile(filename)
        
        do while not f.AtEndOfStream
          s = TrimChars(f.readline, " " + vbTab)
          wscript.echo "|" & s & "|"
        loop
        
        f.close
        
        set f = nothing
        set fso = nothing
        
        ''---
        
        function TrimChars(s, sChars)
          dim n, nLen, nStart
        
          nLen = Len(s)
          if nLen = 0 then
            TrimChars = s
            exit function
          end if
        
          ''- skip leading chars
          n = 1
          do while (n <= nLen) And (InStr(sChars, Mid(s, n, 1)) > 0)
            n = n + 1
          loop
          nStart = n
        
          ''- skip trailing chars
          n = nLen
          do while (n > nStart) And (InStr(sChars, Mid(s, n, 1)) > 0)
            n = n - 1
          loop
        
          ''- return remaining chars
          nLen = n - nStart + 1
          if (nLen > 0) and (nStart <= len(s)) then
            TrimChars = Mid(s, nStart, nLen)
          else
            TrimChars = ""
          end if
        end function
        

        【讨论】:

          【解决方案4】:
          Function LTrimEx(str)
              Do Until x
                  If Left(str, 1) = Chr(32) Or Left(str, 1) = Chr(9) then
                      str = Right(str, Len(str) - 1)
                  Else
                      x = true
                  End If
              Loop
              LTrimEx = str
          End Function
          

          【讨论】: