How to Escape characters in VBScript function embedded in HTA? [duplicate] - windows

I have a set of strings that may or may not have special characters in it.
Example:
Windows Live Fot¢t r
Galer¡a fotogr fica de Windows Live
Windows Live Maker
What i wanna do is to:
check whether the whole string contains a special character in it
If yes, replace these characters with a "?"
I haven't tried anything yet since i'm a newbie in vb scripting.

You can use a regular expression where you add every character that you consider as a non-special character.
stringsToCheck = Array("Windows Live Fot¢t r", _
"Galer¡a fotogr fica de Windows Live", _
"Windows Live Maker")
Set regExp = New RegExp
regExp.IgnoreCase = True
regExp.Global = True
regExp.Pattern = "[^a-z0-9 !?#]" 'Add here every character you don't consider as special character
For each str In stringsToCheck
strProcessed = regExp.Replace(str, "?")
WScript.Echo "Old String: " & str
WScript.Echo "New String: " & strProcessed
Next
Output:
Old String: Windows Live Fot¢t r
New String: Windows Live Fot?t r
Old String: Galer¡a fotogr fica de Windows Live
New String: Galer?a fotogr fica de Windows Live
Old String: Windows Live Maker
New String: Windows Live Maker

You can try below code ..
Function replaceChars(str As String) As String
'msgbox replacechars ("!##$%^&*(") will return !#$%^&()
Dim elem As Variant
replaceChars = str
For Each elem In Array("/", "\", ":", "*", "?", "<", ">", "|", "#", Chr(34))
replaceChars = Replace(replaceChars, elem, "?")
Next
End Function

Try something like this:
strCur="!##$%^&*()?><~`+=|\/.',{}[];:-%_20"
for iCount = 0 to len(strCur )
paragraph= Replace(paragraph, Mid(strCur, iCount + 1, 1), "?")
next
'This line should replace those characters. You'll need a line for each char.
paragraph = Replace$(paragraph, Chr(123), "a")
paragraph = Replace$(paragraph, Chr(173), "A")

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"

search Whole word only in VBscript

I am trying to implement search whole word only in VBScript, I tried appeding characters like space, /, ],) etc. as these characters means end of word. I need to do as many search as the number of characters I want to include using or operator. Is there any way to do it easily in VBScript.
Currently I am doing :-
w_seachString =
searchString & " " or
searchString & "/" or
searchString & "]" or
searchString & ")" or
searchString & "}" or
searchString & "," or
searchString & "."
So eventually I am comparing with lots of combination and looking for an effective way to make my variable w_seachString able to search for whole word only.
Use a regular expression with a word boundary anchor. Demo:
Option Explicit
Function qq(s) : qq = """" & s & """" : End Function
Dim r : Set r = New RegExp
r.Pattern = "\bx\b"
Dim s
For Each s In Split("axb| x |ax|x|\x/|", "|")
WScript.Echo qq(s), CStr(r.Test(s))
Next
output:
cscript 36443611.vbs
"axb" False
" x " True
"ax" False
"x" True
"\x/" True
"" False

How to Remove Specific Special Characters

I have a string like X5BC8373XXX. Where X = a special character equals a Square.
I also have some special characters like \n but I remove them, but I can't remove the squares...
I'd like to know how to remove it.
I Found this method:
Dim Test As String
Test = Replace(Mscomm1.Input, Chr(160), Chr(64) 'Here I remove some of the special characters like \n
Test = Left$(Test, Len(Test) -2)
Test = Right$(Test, Len(Test) -2)
This method DOES remove those special characters, but it's also removing my first character 5.
I realize that this method just remove 2 characters from the left and the right,
but how could I work around this to remove these special characters ?
Also I saw something with vblF, CtrlF something like this, but I couldn't work with this ;\
You can use regular expressions. If you want to remove everything that's not a number or letter, you can use the code below. If there are other characters you want to keep, regular expressions are highly customizable, but can get a little confusing.
This also has the benefit of doing the whole string at once, instead of character by character.
You'll need to reference Microsoft VBScript Regular Expressions in your project.
Function AlphaNum(OldString As String)
Dim RE As New RegExp
RE.Pattern = "[^A-Za-z0-9]"
RE.Global = True
AlphaNum = RE.Replace(OldString, "")
End Function
Cleaning out non-printable characters is easy enough. One brute-force but easily customizable method might be:
Private Function Printable(ByVal Text As String) As String
Dim I As Long
Dim Char As String
Dim Count As Long
Printable = Text 'Allocate space, same width as original.
For I = 1 To Len(Text)
Char = Mid$(Text, I, 1)
If Char Like "[ -~]" Then
'Char was in the range " " through "~" so keep it.
Count = Count + 1
Mid$(Printable, Count, 1) = Char
End If
Next
Printable = Left$(Printable, Count)
End Function
Private Sub Test()
Dim S As String
S = vbVerticalTab & "ABC" & vbFormFeed & vbBack
Text1.Text = S 'Shows "boxes" or "?" depending on the font.
Text2.Text = Printable(S)
End Sub
This will remove control characters (below CHR(32))
Function CleanString(strBefore As String) As String
CleanString = ""
Dim strAfter As String
Dim intAscii As Integer
Dim strTest As String
Dim dblX As Double
Dim dblLen As Double
intLen = Len(strBefore)
For dblX = 1 To dblLen
strTest = Mid(strBefore, dblX, 1)
If Asc(strTest) < 32 Then
strTest = " "
End If
strAfter = strAfter & strTest
Next dblX
CleanString = strAfter
End Function

MS Access 2007 VBA: validating text field with VBA and Chr()

I am trying to validate entry of a form field using the following VBA. This works very well. My problem is this Access app creates a variety of XML data files, and I don't want certain characters within that xml....namely soft-returns (Shift+Enter). I believe that the Chr for this is Chr(11), but I don't think I can just add , Chr(11)) to the end of the array below and this will work...how can I use Chr(#) in link manner?
Dim i, j As Integer
dim myField as variant
varNo = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
If IsNull(Me.FieldValue) = False Then
myField = Me.FieldValue
For i = 0 To UBound(varNo)
j = InStr(1, myField , varNo(i))
If j > 0 Then
MsgBox "Cannot use character:" & Chr(13) & Chr(10) & Chr(13)
& Chr(10) & varNo(i), vbCritical, " Illegal Character"
Exit Sub
Exit For
End If
Next
End If
again the above works great for those things in the array, but I would like to include Chr() as well.
You can build your array with an empty string as the new last element, then change the value of the last element to Chr(11).
varNo = Array("\", "/", ":", "*", "?", """", "<", ">", "|", "")
varNo(UBound(varNo)) = Chr(11)
Actually, I'm unsure why that should be necessary. This works for me ...
varNo = Array("\", "/", ":", "*", "?", """", "<", ">", "|", Chr(11))
Based on the comments, I think it will be useful to confirm the text you're evaluating actually contains the characters you expect. Feed the text to this procedure and examine its output in the Immediate window.
Public Sub AsciiValues(ByVal pInput As String)
Dim i As Long
Dim lngSize As Long
lngSize = Len(pInput)
For i = 1 To lngSize
Debug.Print i, Mid(pInput, i, 1), Asc(Mid(pInput, i, 1))
Next
End Sub
Here are a few notes on another approach:
'' Microsoft VBScript Regular Expressions library
'' or CreateObject ("VBScript.RegExp")
Dim rex As New RegExp
With rex
.MultiLine = False
.Global = True
.IgnoreCase = False
End With
'A line for testing
sLine = "abc" & Chr(11)
'Anything that is NOT a-zA-Z0-9 will be matched
rex.Pattern = "[^a-zA-Z0-9]"
If rex.Test(sLine) Then
Debug.Print "Problem: include only alpha numeric"
End If

Resources