Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to implement regex quantifiers ? #336

Closed
heilingbrunner opened this issue Jan 13, 2023 · 6 comments
Closed

How to implement regex quantifiers ? #336

heilingbrunner opened this issue Jan 13, 2023 · 6 comments

Comments

@heilingbrunner
Copy link

Regex knows quantifiers for example:
[0-9]{3}
for matching three numbers.
I need simple rules to parse this:

1A2BB3CCC

The result should be '1A', '2BB' and '3CCC'. The leading number is the length of the following letters.
I tried:

search
	= (d:digit l:letter{d} {return d + l;})+
letter
	= [a-zA-Z]
digit 'digit'
	= [0-9]

with input 1A2BB3CCC. No success.

Any idea/help ?

Thank you.

@hildjj
Copy link
Contributor

hildjj commented Jan 13, 2023

Being worked on in #291

@heilingbrunner
Copy link
Author

heilingbrunner commented Jan 14, 2023

Any workarounds for limited length ?
I tried this. Do you have any better idea ?

Grammar:

search
	= (t1/t2/t3/t4/t5)+

t1 = d:'1' l:l1 {return d + l;}
t2 = d:'2' l:l2 {return d + l;}
t3 = d:'3' l:l3 {return d + l;}
t4 = d:'4' l:l4 {return d + l;}
t5 = d:'5' l:l5 {return d + l;}

letter
	= [a-zA-Z]

l1 = letter
l2 = $(l1 l1)
l3 = $(l1 l1 l1)
l4 = $(l1 l1 l1 l1)
l5 = $(l1 l1 l1 l1 l1)

Input:
1A2BB3CCC

Result:

[
  '1A',
  '2BB',
  '3CCC'
]

@hildjj
Copy link
Contributor

hildjj commented Jan 14, 2023

Something like this seems to work:

search
	= pair*
    
pair
	= $(n:number l:$letter+ &{ return l.length === n }) 

number
	= n:$[0-9]+ { return parseInt(n, 10) }
    
letter
	= [a-zA-Z]

@heilingbrunner
Copy link
Author

I will try. Thank you !!

@hildjj
Copy link
Contributor

hildjj commented Feb 22, 2023

Now that 3.0.0 is out, you can do this:

search
	= (d:digit l:$letter|d| {return `${d}${l}`;})+
letter
	= [a-zA-Z]
digit 'digit'
	= n:[0-9]+ { return parseInt(n, 10) }

@hildjj
Copy link
Contributor

hildjj commented Feb 22, 2023

I'm going to close this, but open it back up or comment here if 3.0.0 doesn't solve your problem.

@hildjj hildjj closed this as completed Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants