我需要从输出中解析出 n 位数字,我的正则表达式仅解析第一个数字。
regexp "$header(?:.|\\n)*?$detail\\s+:\\s(\\d+)" $output match value
我需要这样,因为多个“标题”包含我的“详细信息”。 我在 tcl 脚本中将此称为正则表达式。 例如
set header "Header1"
set detail "Detail1"
但是 regexp 在 $value 中仅返回 2 而不是 25
有人可以帮忙吗?
谢谢你
输出示例:
Header1
Detail1 : 25
Detail2 : 5
Header2
Detail1 : 18
Detail2 : 200
如果我只有简单的输出(没有多个标题),则使用正则表达式
regexp "$detail\\s+:\\s(\\d+)" $output match value
正确返回n位数字
请注意:
(?:.|\n)
,.
也已经匹配换行符。*?
将正则表达式中所有量词的贪婪设置为惰性,因此\d+
稍后的行为就好像它是\d+?
一样,因此仅抓取模式末尾的单个数字。你可以使用
regexp {header.*?detail\s*:\s*(\d+)(?:\D|$)} $output match value
或 - 仅如果数字右侧始终有非单词字符或字符串结尾:
regexp {header.*?detail\s*:\s*(\d+)\y} $output match value
(?:\D|$)
设置右侧数字边界,\y
设置单词边界(因为我们不知道数字右侧可能有什么样的上下文,所以数字边界是更安全的解决方案)。
查看 Tcl 在线演示。