4 ms·
> In General, the Longer Regex Is the Better Regex I'd rather word this as "more specific is better". Like say for a U.S. phone number (minus area code for sim
by taco_emoji 11y ago
> In General, the Longer Regex Is the Better Regex
I'd rather word this as "more specific is better". Like say for a U.S. phone number (minus area code for simplicity),
\d{3}-?\d{4}
is better than
.*-?.*
because it's more specific.
"Longer is better" is only useful for helping identify which regex is better, not for helping write better regexes.
- leeoniya 11y agoand [0-9] is more specific than \d "In most flavors that support Unicode, \d includes all digits from all scripts." [1] EDIT: But I guess for the majority of use cases it doesn't matter [2] since PCRE is the norm almost everywhere. [1] http://www.regular-expressions.info/shorthand.html http://www.regular-expressions.info/shorthand.html [2] "Notable exceptions are Java, JavaScript, and PCRE. These Unicode flavors match only ASCII digits with \d"
- oftenwrong 11y agoIn many environments, [0-9]{3}-?[0-9]{4} is even more specific (and faster) because \d would match other digit characters outside of [0-9].
- dalore 11y agotaking it to the next level: [0-9][0-9][0-9]-?[0-9][0-9][0-9][0-9]
- bane 11y agoThis is just another statement of precision vs. recall. https://en.wikipedia.org/wiki/Precision_and_recall https://en.wikipedia.org/wiki/Precision_and_recall