Re:Super-expressive – Write regex in natural language
by TeMPOraL on Thursday January 21, 2021 @12:16PM
(#25861324)
> Sadly, JavaScript does not support it. (Big mistake.)
In languages that do not support the x modifier, I just break up my regex into substrings. Something like:
auto regex = "( \w+ )" // Capture the name of the list
+ "\s* = \s*" // spaces = spaces
+ ...
+ "\)"; // Closing paren
Re:Super-expressive – Write regex in natural language
by sktguha on Thursday January 21, 2021 @01:23PM
(#25862144)
You could perhaps use es6 templates for better readability
Re:Super-expressive – Write regex in natural language
by myhf on Thursday January 21, 2021 @12:45PM
(#25861674)
That's a useful technique. Thanks.
Re:Super-expressive – Write regex in natural language
by wendyshu on Thursday January 21, 2021 @01:47PM
(#25862452)
It has the advantage of using normal syntax rather than string literals (AST manipulation, formatting, static analysis, autocomplete, ...).
Re:Super-expressive – Write regex in natural language
by btilly on Thursday January 21, 2021 @04:09PM
(#25864273)
Regular expressions are their own language. The fact that we encode a DSL as a string is the problem for tools, and not the fact that strings are hard to handle.
If you offer a syntax extension other than strings to indicate the DSL coming next, and then have syntax highlighting for that DSL, then it would be fine.
The code that you wind up with is so long that it is hard to read for anyone, whether or not you know regular expressions. I'll never remember what all of the things are called. Anyone who knows regular expressions will find the regular expression readable. Anyone who doesn't is likely to find both relatively similar in effort to learn.
The only tool you need for maintainable regular expressions is the x modifier. That lets you break it up with whitespace and add comments. Here is a real example in code that I wrote for a tool used by people who don't know regular expressions. (This is Python that is parsing out the contents of various arrays in a bash script.)
If you know regular expressions, the comments are superfluous, though breaking up the expression does make it easier to read. If you don't know regular expressions, you should be able to figure out what the code is trying to do and how it does it.How you specify that modifier varies heavily by language. So, for example, in Perl you end your expression with /x. In Python you have to start your regular expression with (?x). In Postgres you pass a third argument with 'x' in it. Sadly, JavaScript does not support it. (Big mistake.)