Is it a good practice to include empty/white space checks in RegEx?
https://softwareengineering.stackexchange.com/questions/364597
-
26-01-2021 - |
Domanda
The goal of the RegEx is to match exactly 6 characters, but in addition it should match empty strings or white space (e.g: ^$|\s|^(\w){6}$
). Is it good practice check for empty string/white space in a RegEx expression, or to perform this check in the higher level code, such as String.IsNullOrWhiteSpace
? There seems to be a code smell to doing it in the RegEx, but I may be imagining things.
Thanks.
Soluzione
Allowing interspersed whitespace and still demanding exactly six characters's worth of input is expensive and should definitely be done outside a regex, e.g. via a replace() before the match is applied.
Allowing whitespace at the start or end is reasonably efficient even within a regular expression, but even so it's probably better just to call trim() (or whatever that's called in C#) first. At the very least, it will make the core purpose of the validation clearer - regexes are hard to understand as it is, no need to burden it with two slightly different purposes.