Created
April 4, 2012 14:28
-
-
Save slevithan/2301755 to your computer and use it in GitHub Desktop.
Grammatical pattern for real numbers using XRegExp.build
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is used in my blog post Creating Grammatical Regexes Using XRegExp.build.