# Was there an attempt to make reusable regular expressions?

In everyday practice I often encounter tasks which would benefit from being able to define aliases for chunks of regular expressions to reuse them later. Typical examples include: parsing a floating point number, a zip code or a telephone number. (Zip code may become particularly unwieldy).

Suppose you could define a grammar for parsing floating point numbers, and then give it an alias, once defined you would be able to reuse this in regular expressions you use afterwards. In some fictional language this could look like this:

float := /[+-]?(\d+|\d*\.d+)(e\d+)?/
sum := /(?R<float>)+(?R<float>)/


This, in principle, wouldn't change anything in terms of expressive power (unless you allow self-reference), but it seems like it could make the practical implementations of regular expressions more concise?

So, my question is: has any language implemented anything like that? Or, and if not, then what would be the reason for not doing so?

Perl 6 supports reusable regular expressions and even grammars. See http://design.perl6.org/S05.html .

• Pre-compiled regexes have been in Perl for a long time, Perl 6 just made them even more powerful (there is no pretense of being actually regular anymore). Many other languages have them as well; the last one I used was ActionScript, but arguably even C's POSIX regexes are reusable in the way you describe. Dec 21, 2014 at 9:13

Lex, the lexical analyser generator, supports this notation. In the "definitions" section, you can define patterns which you can then use in the "rules" section:

DIGIT    [0-9]

%%

{DIGIT}+"."{DIGIT}*  { return T_FNUM; }


Most lexer generators have something similar; ANTLR has "fragments", for example.

• Oh, right, now I wonder why didn't I think of this :) Dec 21, 2014 at 6:06

Let's start with the definition: "A token is a string of one or more characters that is significant as a group" ref. http://en.wikipedia.org/wiki/Lexical_analysis

Truly, while looking for IPv6 (and related regexes) reveals that the use of tokens to represent lexemes is nowhere to find, even though the opportunity about that is plenty; simplicity yields compatibility though: https://www.google.gr/webhp?q=regular+expressions+ipv6#q=regular+expressions+ipv6

Obviously, using/handling the following expression requires a lexical analysis to parse it (such as flex):

sum := /(?R<float>)+(?R<float>)/

It appears that most programming languages call for a library or external tool to manage it, possibly as means to promote the more complete solutions. At least, that's our take for it today :)

• I find your answer very hard to follow and I don't see what most of it has to do with the question. You don't give an example of a programming language that supports combining regexps and I don't see any argument about why that feature isn't included in most languages. Dec 21, 2014 at 9:59