Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex: test for alphanumeric only
#1
Basically I'm trying to eliminate potential problems when exporting user-entered text strings for use downstream of the macro (filenames, html, php, mysql etc.).

What is the best way to do both of these options:

A. Validate that a string contains only contains letters and numbers? (i.e. so I can throw up a message saying "Use only alphanumeric characters" when any special character/non-alphanumeric character exists in a text string)


B. Instead of forcing the user to re-enter/fix string, simply go ahead and replace invalid characters with an underscore like here:

Code:
Copy      Help
u.lcase
u.replacerx(" |-|#" "_")

but without having to list every undesirable character in the replacerx pattern. Essentially the equivalent expression that results in "for each character exists that is not alphanumeric, replace with '_' " (I should mention that I will not have to restore any of the characters removed at a later point).


Thanks in advance for any help!

Steve
#2
Hi Steve,

I don't have the exact answer to your question but want to make sure you are aware of the Reg. Expression Menu on the Floating Toolbar under More Tool (next to the green check mark "Favorites"). Without knowing too much about RegEx, I was able to figure out many things by trial-and-error by just looking through and testing the various options there.

Good luck,
Stuart
#3
Use "character not in range" regular expression.

s.replacerx("[^a-z0-9_]" "_" 1)
#4
Thanks Gintaras...

Stuart -- thanks for the tip, hadn't really used that..

I have definitely recognized the power of RegEx, and have made it my next learning priority (had to break away from my reg scheduled QM/general scripting learning to hastily learn PHP and MYSQL, but now that I've got what I need there, RegEx is next...)

I had actually come across the following...

Code:
Copy      Help
[^A-Za-z0-9_]

...thru RegEx tutorial websites, and tried hard to get it to work, but it was the use of quotes within the ( ) in QM, and not in any of the other scripting example sites that screwed me up.

Not sure if there's a general rule regarding QM and use of quotation marks vs scripting syntax. I understand use of quotes like
Code:
Copy      Help
s.from("a" b "c")
to indicate a and c are not variables but literal text, but then there's this:

To specify "match a, b, or c" in a string in standard reg ex:
Code:
Copy      Help
(a|b|c)
but in QM it is
Code:
Copy      Help
("a|b|c")
which to my first inclination would mean it's looking for the literal string between the quotes...

One day I'll get there...

Steve
#5
Quote:but in QM it is Code:
("a|b|c")

Why? Here () just encloses the argument, and is not necessary. If in examples it is (a|b|c), just add "": "(a|b|c)".


Forum Jump:


Users browsing this thread: 1 Guest(s)