Jack Jack - 2 months ago 22
Ruby Question

Ruby regex specify length of captured group

I need to match a string of variable length(between 5 and 12), composed of uppercase letters and one or more digits between 1 and 8.
How can I specify that I need the whole captured group's length to be between 5 and 12?
I have tried with parenthesis but with no luck.
I have tried this

\s([A-Z]+[1-8]+[A-Z]+){5,12}\s


My idea was to use the quantifier {5,12} to limit the length of the captured group between parenthesis, but clearly it doesn't work like that.

The string needs to be identified inside a normal text just like

"THE STRING I NEED TO DECODE IS SOMETHING LIKE FD1531FHHKWF BUT NOT LIKE g4G58234JJ"

Answer

You actually have two conditions to met:

The length of the match is to be specified with curly brackets {5,12}, and before and after there should be not letters/digits. So:

/(?!\b[A-Z]+\b)\b[A-Z1-8]{5,12}\b/

First, we assure that the lookahead for letters only is negative, then we look for the pattern.