I am trying to use Python regular expression to validate the value of a variable.
The validation rules are as follows:
- The value can contain any of
a-z,A-Z,0-9and*(noblank, no-, no,) - The value can
startwith a number(0-9)or alphabet(a-z, A-Z)or* - The value can
endwith a number(0-9)or alphabet(a-z, A-Z)or* - In the middle, the value can contain a number
(0-9)or alphabet(a-z, A-Z)or* - Any other values must not be allowed
Currently I am using the following snippet of code to do the validation:
import re
data = "asdsaq2323-asds"
if re.compile("[a-zA-Z0-9*]+").match(data).group() == data:
print "match"
else:
print "no match"
I feel there should be a better way of doing the above. I am looking for something like the following:
validate_func(pattern, data)
/* returns data if the data passes the validation rules */
/* return None if the data does not passes the validation rules */
/* should not return part of the data which matches the validation rules */
Does one such build-in function exist?
[\w\d\*]+does not suffice? Best way to test is to do a mass-loop to test all your values you already have (in a list/file?). When a match in the loop fails you should print it out and do more research on it what goes wrong and see how you can optimize your RegEx.