Reputation: 287
Can Anyone help me "Execution flow" of the follwing Regular Expression in TCL.
% regexp {^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$} 9
1 (success)
%
%
% regexp {^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$} 64
1 (success)
% regexp {^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$} 255
1 (success)
% regexp {^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$} 256
0 (Fail)
% regexp {^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$} 1000
0 (Fail)
Can Anyone Please Explain me how these are executing ? I am struggling to understand .
Upvotes: 2
Views: 207
Reputation: 246764
Not an answer to the question, just exploring other ways to do this validation:
proc from_0_to_255 {n} {
expr {[string is integer -strict $n] && 0 <= $n && $n <= 255}
}
from_0_to_255 256 ; # => 0
proc int_in_range {n {from 0} {to 255}} {
expr {[string is integer -strict $n] && $from <= $n && $n <= $to}
}
int_in_range 256 ; # => 0
int_in_range 256 0 1024 ; # => 1
proc int_in_range {n args} {
array set range [list -from 0 -to 255 {*}$args]
expr {
[string is integer -strict $n] &&
$range(-from) <= $n && $n <= $range(-to)
}
}
int_in_range 256 ; # => 0
int_in_range 256 -to 1024 ; # => 1
Upvotes: 2
Reputation: 71538
The regexp first has the anchors ^
and $
around the main capturing group indicated by brackets here ([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])
which means that it is checking the whole string.
Second, inside the capture group, we have 3 parts:
[01]?[0-9][0-9]?
2[0-4][0-9]
25[0-5]
They are separated with |
(or) operators, which means if the string satisfies any of the 3 parts, the match succeeds.
Now, to the individual parts:
[01]?[0-9][0-9]?
This means that it matches 0 or 1 times [01] (either 0 or 1), then any digit, and again any digit, if there's one. Together, this accepts strings like 000
or 199
but nothing above 199.
2[0-4][0-9]
this follows the same logic as above, except that it validates strings with numbers from 200 to 249.
25[0-5]
Finally, this one validates strings with numbers from 250 to 255.
Since there's nothing more, only numbers ranging from 000
to 255
will succeed in the validation.
This is why 9, 64 and 255 passed, but not 256 or 1000.
Upvotes: 6
Reputation: 411
It matches to the following numbers
[01]?[0-9][0-9]? -> 0 - 9, 00 - 99, 000 - 199
2[0-4][0-9] -> 200 - 249
25[0-5] -> 250 - 255
Upvotes: 0
Reputation: 6568
Everything is detailled in http://perldoc.perl.org/perlre.html#Regular-Expressions.
^ Match the beginning of the line
$ Match the end of the line (or before newline at the end)
? Match 1 or 0 times
| Alternation
() Grouping
[] Bracketed Character class
Upvotes: 1