TCL中的反向引用有问题 [英] Having issue with back reference in TCL

查看:125
本文介绍了TCL中的反向引用有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

set a "10.20.30.40"
regsub -all {.([0-9]+).([0-9]+).} $a {\2 \1} b

我正在尝试grep IP地址的第二个和第三个八位字节.

I am trying to grep 2nd and 3rd octet of the IP address.

预期输出:

20 30

实际输出:

20 04 0

这是我的错?

推荐答案

您需要设置匹配组和捕获组的变量,然后才能访问它们.这是一个示例:

You need to set the variables for the match and captured groups, then you can access them. Here is an example:

set a "10.20.30.40"
set rest [regexp {[0-9]+\.([0-9]+)\.([0-9]+)\.[0-9]+} $a match submatch1 submatch2]
puts $submatch1
puts $submatch2

演示的输出

20
30

编辑:

您可以以这种方式使用regsub和backerferences(我现在替换第三个和第二个八位字节,仅用于演示).请注意,必须对文字点进行转义:

You can use regsub and backerferences this way (I am now replacing the 3rd and 2nd octets, just for demonstration). Note that a literal dot must be escaped:

set a "10.20.30.40"
regsub -all {\.([0-9]+)\.([0-9]+)\.} $a {.\2.\1.} b
puts $b

演示的输出:

10.30.20.40

要获取"20 30"字符串,您需要使用

To obtain a "20 30" string, you need to use

regsub -all {^[0-9]+\.([0-9]+)\.([0-9]+)\.[0-9]+$} $a {\1 \2} b

这篇关于TCL中的反向引用有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆