在TCL中遇到后引用问题

时间:2015-05-19 08:47:03

标签: regex tcl regexp-replace regexp-substr

我有以下代码:

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

我正在尝试grep IP地址的第2和第3个八位字节。

预期产出:

20 30

实际输出:

20 04 0

我的错误是什么?

2 个答案:

答案 0 :(得分:2)

我完全远离正则表达式:

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

分割点上的值,取第2和第3个元素,然后用空格连接它们。

答案 1 :(得分:1)

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

create table if not exists z(f1 int, f2 int, f3 int) 
   row format delimited fields terminated by ',' 
   stored as textfile
   LOAD DATA INPATH 'hdfs://localhost:9000/tmp/projects/test.txt' 
   OVERWRITE INTO TABLE z;

the demo

的输出
FAILED: SemanticException [Error 10028]: Line 1:17 Path is not legal 
''hdfs://localhost:9000/tmp/projects/test.txt'': 
Move from: hdfs://localhost:9000/tmp/projects/test.txt to:   
file:/home/zeta/abivin/vCore/AbiServer/warehouse/z is not valid. 
Please check that values for params "default.fs.name" and 
"hive.metastore.warehouse.dir" do not conflict.

修改

您可以通过这种方式使用regsub和backerferences(我现在正在替换第3和第2个八位字节,仅用于演示)。请注意,必须转义文字点:

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

demo的输出:

20
30

要获得“20 30”字符串,您需要使用

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