I’m writing some regex to match lines which contain numeric elements padded with spaces, like -2.45. The regex for this is simple enough:
/(\s*-?\d+\.\d{2})/
However, I have the additional constraint that the whole chunk is limited to exactly seven characters. I can modify the expression to constrain the leading space and digits to within their theoretical maximums:
/(\s{0,3}-?\d{1,4}\.\d{2})/
But this is not the solution, as the \s{0,3} matches independently of the \d{1,4}, so the whole thing could match a chunk anywhere from four to eleven characters.
Is there any way I can constrain a whole group like this to a fixed length?
Edit:
To clarify, I’m processing lines with three of these seven character groups separated with three spaces, so the larger regex goes along the lines of:
/^(fixed length stuff at start of line)(7 char chunk)\s{3}(2nd 7 char chunk)\s{3}(3rd 7 char chunk)$/
Mixed in are other lines which have only one or two of these numeric groups in, lines with presentational junk, and lines with other (possibly unknowable) content so I’m looking to be quite precise in what I match.
You can use a lookahead assertion (and you don’t need the parentheses):
You might need some anchors around the regex to ensure that you don’t match beyond the seven characters, depending on what delimits these elements, for example
to ensure that the number actually ends after the
\.d{2}part.