Having issue with back reference in TCL

微笑、不失礼 提交于 2019-12-08 09:48:16

问题


I have the following code:

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

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

Expected output:

20 30

Actual output:

20 04 0

What is my mistake here?


回答1:


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

Output of the demo

20
30

EDIT:

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

Output of the demo:

10.30.20.40

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

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



回答2:


I'd stay away from regular expressions altogether:

set b [join [lrange [split $a .] 1 2]]

Split the value on dots, take the 2nd and 3nd elements, and join them with a space.



来源:https://stackoverflow.com/questions/30320793/having-issue-with-back-reference-in-tcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!