3 ms·
A lot of time I want to check for valid identifier: if not re.match('^[a-z0-9_]+$', user): raise SomeException("invalid username") as written, the
by theamk 9mo ago
A lot of time I want to check for valid identifier:
if not re.match('^[a-z0-9_]+$', user):
raise SomeException("invalid username")
as written, the code above is incorrect - it will happily accept "john\n", which can cause all sort of havoc down the line
- extraduder_ire 9mo agoShouldn't you use the match returned from the string? Or use .fullmatch() (added 3.4) to match the whole string.
- theamk 9mo agoIn general no, you should not use match from the string. If you are getting input from user, you want a more complex processing (like stripping all whitespace), and if you are getting input from API calls, you want to either use specified name as-is, or fail. Yes, fullmatch() will help, and so will \Z. It's just that it is so easy to forget...