Trim leading spaces including tabs

后端 未结 4 993
醉酒成梦
醉酒成梦 2020-12-19 13:20

I need to read files using vbscript and remove all leading spaces including any tabs. I now LTRIM will remove the leading spaces but how do I remove tabs also.

Thank

相关标签:
4条回答
  • 2020-12-19 13:53

    For a both left and right trim (including tabs, carriage return, line feeds, spaces) in a multiline string this will work.

    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
    
    0 讨论(0)
  • 2020-12-19 14:03

    This function removes all leading whitespace (spaces, tabs etc) from a string:

    Function LTrimEx(str)
      Dim re
      Set re = New RegExp
      re.Pattern = "^\s*"
      re.Multiline = False
      LTrimEx = re.Replace(str, "")
    End Function
    
    0 讨论(0)
  • 2020-12-19 14:04

    Andrew's answer is not correct. LTrim, RTrim and Trim only removes spaces, not tabs.

    I reformatted your code, and added a function to strip any leading or trailing characters.

    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
    
    0 讨论(0)
  • 2020-12-19 14:10
    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
    
    0 讨论(0)
提交回复
热议问题