I been using the following code to filter out illegal characters from a textfield for a valid Windows path. However, now I have a need for only alphanumeric characters (0-9, A-Z, a-z) to pass. Is there any easy way add all non-alphanumeric characters to this array, as opposed to typing each one in manually? Adding the few illegal characters below was easy for a Windows path, but I can’t even image putting every non-alphanumeric in one by one!
dim INVALIDCHAR() as String
INVALIDCHAR=Array(",", "?", "/", "\", ":", ">", "<", "*", "|", """")
for each NAME as string in INVALIDCHAR
if TEXTFIELD1.Text.InStr(NAME) <> 0 then
MsgBox "Entry can only contain alphanumeric characters."
return
end
next
RegEx is your friend here. If you want to include the underscore character as well, then the regex library used by Xojo support \w to mean that set and \W to mean NOT in that set. So just test your filename against \W and if there is a match, then issue your MsgBox. If you don’t want to include the underscore, then test against [^A-Za-z0-9] or whatever group of characters you prefer.
dim rx as new RegEx
rx.SearchPattern = "(?Ui-ms)[^a-zA-Z0-9]"
rx.ReplacementPattern = "_"
dim rxOptions as RegExOptions = rx.Options
rxOptions.LineEndType = 4
rxOptions.ReplaceAllMatches = true
dim replacedText as string = rx.Replace( sourceText )