Created
October 21, 2013 01:55
-
-
Save weshoke/7077605 to your computer and use it in GitHub Desktop.
Parsing integers with LPEG in Lua
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
| local lpeg = require"lpeg" | |
| local P, R, S = lpeg.P, lpeg.R, lpeg.S | |
| -- Any non-zero digit: (R stands for Range) | |
| local nonzero = R"19" | |
| -- Only zero: (P stands for Pattern) | |
| local zero = P"0" | |
| -- Any digit: | |
| local digit = R"09" | |
| -- Match a sqeuence of one or more numbers not starting with zero (aka positive numbers) | |
| local positive = nonzero * (zero + nonzero)^0 | |
| -- Match the natural numbers (positive numbers including zero) | |
| local natural = zero + positive | |
| -- Match all integers (including negative numbers) | |
| local integer = P"-"^-1 * natural * P(-1) | |
| print(integer:match"1") --> '2', match successful | |
| print(integer:match"0") --> '2', match successful | |
| print(integer:match"109234") --> '7', match successful | |
| print(integer:match"-10") --> '4', match successful | |
| print(integer:match"-0") --> '3', match successful | |
| print(integer:match"012") --> 'nil', match unsuccessful | |
| print(integer:match"2a12") --> 'nil', match unsuccessful |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment