Vbscript Trim function - vbscript

I have a script that reads in a comma delimited text file, however whenever I use Trim(str) on one of the values I have extracted in the file, it won't work...
My Text File:
some string, anotherstring, onelaststring
some string, anotherstring, onelaststring
some string, anotherstring, onelaststring
some string, anotherstring, onelaststring
My Script:
Dim fso, myTxtFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set myTxtFile = fso.OpenTextFile("mytxt.txt")
Dim str, myTxtArr
txtContents myTxtFile.ReadAll
myTxtFile.close
myTxtArr = Split(txtContents, vbNewLine)
For each line in myTxtArr
tLine = Split(tLine, ",")
Trim(tLine(1))
If tLine(1) = "anotherstring" Then
MsgBox "match"
End If
Next
My script never reaches "match" and I'm not sure why.

Trim() is a function that returns the trimmed string. Your code uses it improperly. You need to use the returned value:
myTxtArr(1) = Trim(myTxtArr(1))
or use another variable to store the value, and use that separate variable in the comparison,
trimmedStr = Trim(myTxtArr(1))
If trimmedStr = "anotherstring" Then
or you can just use the function return value directly in the comparison,
If Trim(myTxtArr(1)) = "anotherstring" Then
Here's a corrected version of that portion of your code:
For each line in myTxtArr
tLine = Split(line, ",")
tLine(1) = Trim(tLine(1))
If tLine(1) = "anotherstring" Then
MsgBox "match"
End If
Next

Related

Remove unnecessary data/Spaces in CSV

I need help on how to remove spaces/emtpy in data without compromising spaces on other data. Here's my sample data.
12345," ","abcde fgh",2017-06-06,09:00,AM," ", US
expected output:
12345,,"abcde fgh",2017-06-06,09:00,AM,, US
since " " should be considered as null.
I tried the Trim() function but it did not work. I also tried Regex pattern but still no use.
Here's my sample function.
Private Sub Transform(delimiter As String)
Dim sFullPath As String
Dim strBuff As String
Dim re As RegExp
Dim matches As Object
Dim m As Variant
If delimiter <> "," Then
strBuff = Replace(strBuff, delimiter, ",")
Else
With re
.Pattern = "(?!\B""[^""]*)" & delimiter & "(?![^""]*""\B)"
.IgnoreCase = False
.Global = True
End With
Set matches = re.Execute(strBuff)
For Each m In matches
strBuff = re.Replace(strBuff, ",")
Next
Set re = Nothing
Set matches = Nothing
End If
End Sub
I think you're on the right track. Try using this for your regular expression. The two double quotes in a row are how a single double quote is included in a string literal. Some people prefer to use Chr(34) to include double quotes inside a string.
\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)
Using that expression on your example string
12345," ","abcde fgh",2017-06-06,09:00,AM," ", US
yields
12345,"","abcde fgh",2017-06-06,09:00,AM,"", US
Example function
Private Function Transform(ByVal strLine As String) As String
Dim objRegEx As RegExp
On Error GoTo ErrTransForm
Set objRegEx = New RegExp
With objRegEx
.Pattern = "\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)"
.IgnoreCase = False
.Global = True
Transform = .Replace(strLine, "")
End With
ExitTransForm:
If Not objRegEx Is Nothing Then
Set objRegEx = Nothing
End If
Exit Function
ErrTransForm:
'error handling code here
GoTo ExitTransForm
End Function
And credit where credit is due. I used this answer, Regex Replace Whitespaces between single quotes as the basis for the expression here.
I would add an output string variable and have a conditional statement saying if the input is not empty, add it on to the output string. For example (VB console app format with the user being prompted to enter many inputs):
Dim input As String
Dim output As String
Do
input = console.ReadLine()
If Not input = " " Then
output += input
End If
Loop Until (end condition)
Console.WriteLine(output)
You can throw any inputs you don't want into the conditional to remove them from the output.
Your CSV file isn't correctly formatted.
Double quote shouldn't exists, then open your CSV with Notepad and replace them with a null string.
After this, you now have a real CSV file that you can import whitout problems.

What does these lines of code do in VBScript?

I am converting them to Jython script and I felt all it does is remove spaces at ends
function test (strField)
Dim re
Set re = New RegExp
re.Pattern = "^\s*"
re.MultiLine = False
strField = re.replace(strField,"")
End Function
It uses the RegExp object in VBScript to check for whitespace \s at the start of the variable passed into the Sub / Function called strField. Once it identifies the whitespace it uses the Replace() method to remove any matched characters from the start of the string.
As #ansgar-wiechers has mentioned in the comments it is just an all whitespace implementation of the LTrim() function.
I'm assuming this is meant to be a Function though (haven't tested but maybe VBScript accepts Fun as shorthand for Function, not something I'm familiar with personally) with that in mind it should return the modified strField value as the result of the function. Would also recommend using ByVal to stop the strField value after it is manipulated bleeding out of the function.
Function test(ByVal strField)
Dim re
Set re = New RegExp
re.Pattern = "^\s*"
re.MultiLine = False
strField = re.replace(strField,"")
test = strField
End Function
Usage in code:
Dim testin: testin = " some whitespace here"
Dim testout: testout = test(testin)
WScript.Echo """" & testin & """"
WScript.Echo """" & testout & """"
Output:
" some whitespace here"
"some whitespace here"

VBScript Replace specific value with regex and modify text file

I know there are a lot questions similar to this one but i couldn't find the right answer for me. I need to replace all phrases in xml file that starts and ends with % (e.g. %TEST% or %TEST-NEW% )
So far i have these tryouts:
This was my test one that works in the console but has only 1 line of string
zone = "<test>%TEST%</test>"
MsgBox zone
'Setting the regex and cheking the matches
set regex = New RegExp
regex.IgnoreCase = True
regex.Global = True
regex.Pattern = "%.+%"
Set myMatches = regex.execute(zone)
For each myMatch in myMatches
Wscript.echo myMatch
result = Replace(zone,myMatch,"")
next
MsgBox result
but when i try to do the same from a file with this...
Dim objStream, strData, fields
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\test\test.xml")
strData = objStream.ReadText()
Wscript.echo strData
set regex = New RegExp
regex.IgnoreCase = True
regex.Global = True
regex.Pattern = "%.+%"
Set myMatches = regex.execute(strData)
For each myMatch in myMatches
Wscript.echo myMatch
result = Replace(strData,myMatch,"")
next
Wscript.echo result
...the first echo returns correctly the contains of the file and then the second echo in the loop echoes all the matches that i need to replace , but the last echo return the same result as the first (nothing is being replaced)
The xml looks like this (just for example):
<script>%TEST%</script>
<value>%VALUE%</value>
<test>%TEST%</test>
P.S. I need to loop through xml files in a specific folder and replace the phrase from above. Can anyone help?
The final script that works for me(big thanks to Tomalak):
Option Explicit
Dim path, doc, node, placeholder,srcFolder,FSO,FLD,fil
Set placeholder = New RegExp
placeholder.Pattern = "%[^%]+%"
placeholder.Global = True
srcFolder = "C:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FLD = FSO.GetFolder(srcFolder)
For each fil In FLD.Files
if LCase(FSO.GetExtensionName(fil.Name)) = "xml" Then
path = "C:\test\" & fil.Name
' 1. parse the XML into a DOM
Set doc = LoadXmlDoc(path)
' 2. select and modify DOM nodes
For Each node In doc.selectNodes("//text()|//#*")
node.nodeValue = SubstitutePlaceholders(node.nodeValue)
Next
' 3. save modified DOM back to file
doc.save path
End If
Next
' --------------------------------------------------------------------------
Function LoadXmlDoc(path)
Set LoadXmlDoc = CreateObject("MSXML2.DomDocument.6.0")
LoadXmlDoc.async = False
LoadXmlDoc.load path
If LoadXmlDoc.parseError.errorCode <> 0 Then
WScript.Echo "Error in XML file."
WScript.Echo LoadXmlDoc.parseError.reason
WScript.Quit 1
End If
End Function
' --------------------------------------------------------------------------
Function SubstitutePlaceholders(text)
Dim match
For Each match In placeholder.Execute(text)
text = Replace(text, match, GetReplacement(match))
Next
SubstitutePlaceholders = text
End Function
' --------------------------------------------------------------------------
Function GetReplacement(placeholder)
Select Case placeholder
Case "%TEST%": GetReplacement = "new value"
Case "%BLA%": GetReplacement = "other new value"
Case Else: GetReplacement = placeholder
End Select
End Function
' --------------------------------------------------------------------------
Never use regular expressions on XML files, period.
Use an XML parser. It will be simpler, the code will be easier to read, and most importantly: It will not break the XML.
Here is how to modify your XML document in the proper way.
Option Explicit
Dim path, doc, node, placeholder
Set placeholder = New RegExp
placeholder.Pattern = "%[^%]+%"
placeholder.Global = True
path = "C:\path\to\your.xml"
' 1. parse the XML into a DOM
Set doc = LoadXmlDoc(path)
' 2. select and modify DOM nodes
For Each node In doc.selectNodes("//text()|//#*")
node.nodeValue = SubstitutePlaceholders(node.nodeValue)
Next
' 3. save modified DOM back to file
doc.save path
' --------------------------------------------------------------------------
Function LoadXmlDoc(path)
Set LoadXmlDoc = CreateObject("MSXML2.DomDocument.6.0")
LoadXmlDoc.async = False
LoadXmlDoc.load path
If LoadXmlDoc.parseError.errorCode <> 0 Then
WScript.Echo "Error in XML file."
WScript.Echo LoadXmlDoc.parseError.reason
WScript.Quit 1
End If
End Function
' --------------------------------------------------------------------------
Function SubstitutePlaceholders(text)
Dim match
For Each match In placeholder.Execute(text)
text = Replace(text, match, GetReplacement(match))
Next
SubstitutePlaceholders = text
End Function
' --------------------------------------------------------------------------
Function GetReplacement(placeholder)
Select Case placeholder
Case "%TEST%": GetReplacement = "new value"
Case "%BLA%": GetReplacement = "other new value"
Case Else: GetReplacement = placeholder
End Select
End Function
' --------------------------------------------------------------------------
The XPath expression //text()|//#* targets all text nodes and all attribute nodes. Use a different XPath expression if necessary. (I will not cover XPath basics here, there are plenty of resources for learning it.)
Of course this solution uses regular expressions, but it does that on the text values that the XML structure contains, not on the XML structure itself. That's a crucial difference.

Reading and storing cyrillic in variables

I am trying to read cyrillic values separated by ; from a file, scan every line for match in the first value and assign the following values to variables.
Here is the code I have so far:
Dim objStream, strData, splitted
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
splitted = split(strData, ";")
textfile.txt contains something like this:
Име;Адрес;Телефон;
Име2;Адрес2;Телефон2;
I will have a variable like this:
searchFor = "Име"
and the script must assign Адрес and Телефон to variables.
Basically, I need to search for the name(Име or Име2) in every line from the textfile and then assign the second and the third values of that line to variables.
Currently strData gets the data but it's stored as a string that I cannot manipulate or don't know how.
First split the text at newlines, then split each line at semicolons, then check if the first field matches your search value. Example:
searchFor = "Име"
For Each line In Split(strData, vbNewLine)
fields = split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next
Note that you must save the script in Unicode format, lest your search string be botched.
Here is the complete final working script (Thanks to Ansgar Wiechers!)
Dim objStream, strData, fields
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
searchFor = "Име"
MsgBox searchFor
For Each line In Split(strData, vbNewLine)
fields = Split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next

Using VB6, how can I check whether a sub-string is at the beginning of a another string?

I need to go through a text file and check whether the start of each line begins with "Attribute". How should I do this in VB6?
Use a Regex. You will have to include the VBScript Regular Expressions library in your references.
Dim reg As new Scripting.Regex().
reg.Pattern = "^Attribute"
If reg.Match(line) Then
' Do Something
End If
Dim sInput As String, check as Boolean
check = true
Open "myfile" For INPUT As #txtFile
While Not EOF(txtFile)
Input #txtFile, sInput
If Not Mid(sInput,1,9) = "ATTRIBUTE" Then
check = false
End if
sInput = ""
Wend
Close #txtFile
If check = true at the end, all lines start with "ATTRIBUTE", otherwise they do not.
You could try something like this (code not tested) -
Dim ParseDate, AllLinesStartWithAttribute, fso, fs
AllLinesStartWithAttribute = False
Set fso = CreateObject("Scripting.FileSystemObject")
Set fs = fso.OpenTextFile("c:\yourfile", 1, True)
Do Until fs.AtEndOfStream
If Left(fs.ReadLine, 9) <> "Attribute" Then
AllLinesStartWithAttribute = False
Exit Do
End If
Loop
fs.Close
Set fs = Nothing
Once the code is run if the AllLinesStartWithAttribute value is set to true then all lines in your file begin with 'Attribute'. Please note that this code is case sensitive.
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim str As String
Set ts = fso.OpenTextFile(MyFile)
Do While Not ts.AtEndOfStream
str = ts.ReadLine
If InStr(str, "Attribute") = 1 Then
' do stuff
End If
Loop

Resources