5 ms·
Why would you want a regular expression to detect a valid regular expression?
by ChrisSD 7y ago
Why would you want a regular expression to detect a valid regular expression?
- afiori 7y agoProbably to check if a regular expression is valid
- xfitm3 7y agoCouldn't you just compile it and check for return value?
- ChrisSD 7y agoYes, checking to see if a regular expression is valid is useful but that wasn't what I was asking. Why specifically would you want to use a regular expression for this job?
- Lordarminius 7y agoMaybe because you can :/
- afiori 7y agoThe simplest explanation is because you already have a lot of functionality implemented this way. Still probably the library you are using exposes a validation function...
- braythwayt 7y agoA regular expression is a domain-specific language that defines a language consisting of all the strings it matches. In principle, this serves as executable documentation. A regular expression that matches valid regular expressions could be viewed as a human-readable documentation of valid regular expression syntax that has the valuable side-effect of being executable. If, instead, we detect whether a string is a regular expression by compiling it, we may find it very difficult to read the compiler source code. It is much more work to make an optimized regular expression engine that is also self-documenting than a regular expression.
- ChrisSD 7y agoI think we have different definitions of human readable documentation. I'd find normal code, with or without appropriate comments, far more readable than a mess of regex symbols.
- braythwayt 7y agoRegular expressions are not my favourite either, but one thing I will say is that normal code becomes difficult to read over time as features are bolted on and optimizations are added to address performance concerns. Whereas, some form of executable DSL can serve as self-testing documentation indefinitely. DSLs can provide a separation of concerns, where the syntax is designed for readability, and the engine is designed for performance. Modern Regexen are a dumpster fire, of course, but you asked why someone might want to, not whether this is something Everyone might want to do.
- lvh 7y agoIf you could do this with a proper regex: they’re easy to parse and don’t have a lot of structure, so you can do neat things like produce generators from them. Now, you can get your regex for regexes to produce new regexes! This can be useful if you want to do generative testing.