[英]Use Regexp to match a certain repetitive pattern string input in TCL
I would like to check if an input matches a specific repetitive pattern.我想检查输入是否与特定的重复模式匹配。
Pattern = 3 Uppercase character follow by 2 digits and being separated by ':'模式 = 3 大写字符后跟 2 位数字并由 ':' 分隔
I have try the below regexp but it is not working.我尝试了下面的正则表达式,但它不起作用。
# This should return "Input Criteria Meet"
set user_input_1 "AAB22:GHD23:UDJ29:YUD51"
if {[regexp {^[[A-Z]{3}[0-9]{2}:]+$} $user_input_1]} {
puts "Input Criteria Meet"
} else {
puts "Input Criteria not meet"
}
How about this?这个怎么样? Assuming you have 4 parts, otherwise replace {4}
with +
.假设您有 4 个部分,否则将{4}
替换为+
。
^([A-Z]{3}\d{2}(:|$)){4}\b
Explanation:解释:
^
Start of string ^
字符串开头(
Start of capture group (
捕获组的开始[AZ]{3}
Three uppercase characters [AZ]{3}
三个大写字符\d{2}
Two digit characters \d{2}
两位数字字符(
Start of OR capture group (
OR 捕获组的开始
:|$
Colon character OR end of string :|$
冒号字符或字符串结尾)
End of OR capture group )
OR 捕获组结束{4}
Four instances of the preceeding capture group {4}
先前捕获组的四个实例\b
Word boundary to prevent a trailing :
to be matched. \b
单词边界以防止尾随:
被匹配。You could use你可以使用
^[A-Z]{3}[0-9]{2}(?::[A-Z]{3}[0-9]{2}){3}$
^
Start of string ^
字符串开头[AZ]{3}[0-9]{2}
Match 3 times AZ and 2 times a digit 0-9 [AZ]{3}[0-9]{2}
匹配 3 次 AZ 和 2 次数字 0-9(?:
Non capture group (?:
非捕获组
:[AZ]{3}[0-9]{2}
Match :
3 times AZ and 2 times a digit 0-9 :[AZ]{3}[0-9]{2}
匹配:
3 次 AZ 和 2 次数字 0-9){3}
Close non capture group and repeat 3 times ){3}
关闭非捕获组并重复 3 次$
End of string $
字符串结尾Sometimes it is easier to not use a regular expression for everything, and to instead use one in concert with another operation.有时,对所有事情都不使用正则表达式会更容易,而是将一个正则表达式与另一个操作一起使用。 Some types of validation are also much clearer when put in a helper procedure:某些类型的验证在放入辅助过程时也会更加清晰:
proc ValidateString {input} {
foreach part [split $input ":"] {
# A regular expression is the easiest way of validating the interior pieces
if {![regexp {^[A-Z]{3}[0-9]{2}$} $part]} {
return false
}
}
return true
}
set user_input_1 "AAB22:GHD23:UDJ29:YUD51"
if {[ValidateString $user_input_1]} {
puts "Input Criteria Meet"
} else {
puts "Input Criteria not meet"
}
You could instead use a more complex RE like this:您可以改为使用更复杂的 RE,如下所示:
# ...
if {[regexp {^[A-Z]{3}[0-9]{2}(:[A-Z]{3}[0-9]{2})*$} $user_input_1]} {
# ...
but that's significantly harder to read unless you switch to extended form, and lacks the clearer mnemonics of a named helper procedure so I wouldn't really recommend it.但是除非您切换到扩展形式,否则这将很难阅读,并且缺少命名帮助程序的更清晰的助记符,因此我不会真正推荐它。
I have tried out the following and it is working.我已经尝试了以下方法并且它正在工作。
regexp {^[A-Z]{2}[0-9]{2}(:[A-Z]{2}[0-9]{2})+$} $user_input_1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.