regex - 如何使用 Tcl 正则表达式提取所有匹配项?

标签 regex tcl

大家好,我想要这个正则表达式的解决方案,我的问题是提取 H'xxxx 形式的所有十六进制数字,我使用了这个正则表达式,但我没有得到所有十六进制值,只有我得到一个数字,如何从该字符串中获取整个十六进制数字

set hex "V5CCH,IA=H'22EF&H'2354&H'4BD4&H'4C4B&H'4D52&H'4DC9"
set res [regexp -all {H'([0-9A-Z]+)&} $hex match hexValues]
puts "$res H$hexValues"

我得到的输出是 5 H4D52

最佳答案

-all -inline

来自the documentation :

-all : Causes the regular expression to be matched as many times as possible in the string, returning the total number of matches found. If this is specified with match variables, they will contain information for the last match only.

-inline : Causes the command to return, as a list, the data that would otherwise be placed in match variables. When using -inline, match variables may not be specified. If used with -all, the list will be concatenated at each iteration, such that a flat list is always returned. For each match iteration, the command will append the overall match data, plus one element for each subexpression in the regular expression.

因此,要在 Tcl 中将所有匹配项(包括按组捕获的内容)作为平面列表返回,您可以编写:

set matchTuples [regexp -all -inline $pattern $text]

如果模式有组 0…N-1 ,那么每场比赛都是 N - 列表中的元组。因此,实际匹配的数量是该列表的长度除以 N 。然后您可以使用foreachN用于迭代列表中每个元组的变量。

如果N = 2例如,您有:

set numMatches [expr {[llength $matchTuples] / 2}]

foreach {group0 group1} $matchTuples {
   ...
}

引用文献

<小时/>

示例代码

这是针对此特定问题的解决方案,并使用输出作为注释进行注释 ( see also on ideone.com ):

set text "V5CCH,IA=H'22EF&H'2354&H'4BD4&H'4C4B&H'4D52&H'4DC9"
set pattern {H'([0-9A-F]{4})}
 
set matchTuples [regexp -all -inline $pattern $text]
 
puts $matchTuples
# H'22EF 22EF H'2354 2354 H'4BD4 4BD4 H'4C4B 4C4B H'4D52 4D52 H'4DC9 4DC9
# \_________/ \_________/ \_________/ \_________/ \_________/ \_________/
#  1st match   2nd match   3rd match   4th match   5th match   6th match
 
puts [llength $matchTuples]
# 12
 
set numMatches [expr {[llength $matchTuples] / 2}]
puts $numMatches
# 6
 
foreach {whole hex} $matchTuples {
   puts $hex
}
# 22EF
# 2354
# 4BD4
# 4C4B
# 4D52
# 4DC9
<小时/>

关于模式

请注意,我稍微改变了模式:

  • 而不是 [0-9A-Z]+ ,例如[0-9A-F]{4}更具体的是精确匹配 4 个十六进制数字
  • 如果您坚持匹配& ,那么最后一个十六进制字符串(输入中的 H'4DC9 )无法匹配
    • 这解释了为什么您会得到 4D52在原始脚本中,因为这是与 & 的最后一个匹配
    • 也许摆脱 & ,或使用(&|$)相反,即 &或字符串 $ 的结尾.

引用文献

关于regex - 如何使用 Tcl 正则表达式提取所有匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3369458/

相关文章:

Python 正则表达式和 Pandas

php - 如何从 Twitter 主题标签中删除#?

postgresql - 在二进制 Windows (7) 64 位 Enterprise DB 安装上创建 PLTCL 语言时出错

javascript - ace 编辑器非捕获组问题(?:)

PHP 正则表达式和相邻的捕获组

linux - 无法使用 expect 脚本运行远程 ssh 命令

tcl - 使用 expect 到 SSH 到服务器并执行命令

c - Tcl 和 C 线程的动态共享内存空间

linux - TCL,预计为 : Multiple files w/SCP

regex - 用于Google Analytics(分析)中动态目标页面的正则表达式