设定结果" 1 1.1.1.1 \ n2 2.2.2.2 \ n3 3.3.3.3 \ n4 4.4.4.4 \ n5 399.399.1.1" put"结果o / p \ n $ result"
输出:
Result o/p
1 1.1.1.1
2 2.2.2.2
3 3.3.3.3
4 4.4.4.4
问题 - 如何使用TCL正则表达式提取对应于端口的有效IP地址,即
User Input - 2 , Expected Output - 2.2.2.2 (Valid IP)
User Input - 3 , Expected Output - 399.399.1.1 (InValid IP)
答案 0 :(得分:0)
首先,由于输入是有效列表,我会将其“转换”为数组:
% set result "1 1.1.1.1\n2 2.2.2.2\n3 3.3.3.3\n4 4.4.4.4\n5 399.399.1.1"
% array set results $result
% parray results
results(1) = 1.1.1.1
results(2) = 2.2.2.2
results(3) = 3.3.3.3
results(4) = 4.4.4.4
results(5) = 399.399.1.1
% set user_input 5
% puts $results($user_input)
399.399.1.1
然后,使用彼得的建议:
% set fmt {User Input - %d, Expected Output - %s (%s IP)}
% set user_input 5
% puts [format $fmt $user_input $results($user_input) [expr {[::ip::version $results($user_input)] > 0 ? "Valid" : "Invalid"}]]
User Input - 5, Expected Output - 399.399.1.1 (Invalid IP)
% set user_input 4
% puts [format $fmt $user_input $results($user_input) [expr {[::ip::version $results($user_input)] > 0 ? "Valid" : "Invalid"}]]
User Input - 4, Expected Output - 4.4.4.4 (Valid IP)
使用正则表达式:
% set re_octet {\m(?:\d\d?|1\d\d|2[0-4]\d|25[0-5])\M}
% set re_ip "$re_octet\\.$re_octet\\.$re_octet\\.$re_octet"
% set user_input 5
% puts [format $fmt $user_input $results($user_input) [expr {[regexp $re_ip $results($user_input)] ? "Valid" : "Invalid"}]]
User Input - 5, Expected Output - 399.399.1.1 (Invalid IP)
% set user_input 4
% puts [format $fmt $user_input $results($user_input) [expr {[regexp $re_ip $results($user_input)] ? "Valid" : "Invalid"}]]
User Input - 4, Expected Output - 4.4.4.4 (Valid IP)