Skip to content

Instantly share code, notes, and snippets.

@slevithan
Created April 4, 2012 14:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slevithan/2301755 to your computer and use it in GitHub Desktop.
Save slevithan/2301755 to your computer and use it in GitHub Desktop.
Grammatical pattern for real numbers using XRegExp.build
// Creating a grammatical pattern for real numbers using XRegExp.build
/*
* Approach 1: Make all of the subpatterns reusable
*/
var lib = {
digit: /[0-9]/,
exponentIndicator: /[Ee]/,
digitSeparator: /[_,]/,
sign: /[+-]/,
point: /[.]/
};
lib.preexponent = XRegExp.build('(?xn)\
{{sign}} ? \
(?= {{digit}} \
| {{point}} \
) \
( {{digit}} {1,3} \
( {{digitSeparator}} ?\
{{digit}} {3} \
) * \
) ? \
( {{point}} \
{{digit}} + \
) ? ',
lib
);
lib.exponent = XRegExp.build('(?x)\
{{exponentIndicator}}\
{{sign}} ? \
{{digit}} + ',
lib
);
lib.real = XRegExp.build('(?x)\
^ \
{{preexponent}}\
{{exponent}} ? \
$ ',
lib
);
/*
* Approach 2: No need to reuse the subpatterns. {{sign}} and {{digit}} are defined twice, but that
* can be avoided by defining them before constructing the main pattern (see Approach 1).
*/
var real = XRegExp.build('(?x)\
^ \
{{preexponent}}\
{{exponent}} ? \
$ ',
{
preexponent: XRegExp.build('(?xn)\
{{sign}} ? \
(?= {{digit}} \
| {{point}} \
) \
( {{digit}} {1,3} \
( {{digitSeparator}} ?\
{{digit}} {3} \
) * \
) ? \
( {{point}} \
{{digit}} + \
) ? ',
{
sign: /[+-]/,
digit: /[0-9]/,
digitSeparator: /[_,]/,
point: /[.]/
}
),
exponent: XRegExp.build('(?x)\
{{exponentIndicator}}\
{{sign}} ? \
{{digit}} + ',
{
sign: /[+-]/,
digit: /[0-9]/,
exponentIndicator: /[Ee]/
}
)
}
);
/*
* Matches:
* -0
* 1,000
* 10_000_000
* 1,111.1111
* 01.0
* .1
* 1e2
* +1.1e-2
*
* Doesn't match:
* ,100
* 10,00
* 1,0000
* 1.
* 1.1,111
* 1k
*/
@slevithan
Copy link
Author

This is used in my blog post Creating Grammatical Regexes Using XRegExp.build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment