A regular expression that matches a fixed-length fragment with variable-length elements

I am writing some regular expression to match strings that contain numeric elements filled with spaces, for example -2.45 . The regular expression for this is quite simple:

 /(\s*-?\d+\.\d{2})/ 

However, I have an additional restriction that the entire fragment is limited to exactly seven characters. I can change the expression to limit the leading space and numbers to their theoretical maximums:

 /(\s{0,3}-?\d{1,4}\.\d{2})/ 

But this is not a solution, since \s{0,3} matches regardless of \d{1,4} , so all this can correspond to a fragment of four to eleven characters.

Is there any way to limit the whole group as a fixed length?

Edit:

To clarify, I process strings with three of these seven groups of characters separated by three spaces, so the larger regular expression goes along the lines:

 /^(fixed length stuff at start of line)(7 char chunk)\s{3}(2nd 7 char chunk)\s{3}(3rd 7 char chunk)$/ 

Mixed ones are other lines that contain only one or two of these number groups, lines with a presentation unwanted file, and lines with other (possibly unrecognizable) content, so I think I'm pretty accurate in what I'm matching.

+4
source share
1 answer

You can use lookahead expression (and you don't need parentheses):

 /(?=[\s\d-]{4}\.\d{2})\s*-?\d+\.\d{2}/ 

You might need some bindings around the regex to make sure you don't match seven characters, depending on what restricts these elements, e.g.

 /(?=[\s\d-]{4}\.\d{2}\b)\s*-?\d+\.\d{2}\b/ 

to make sure that the number really ends after the \.d{2} .

+4
source

Source: https://habr.com/ru/post/1392744/


All Articles