使用正则表达式在大括号内提取文件的一部分

时间:2013-07-18 08:47:04

标签: regex tcl

我有一个以下格式的文件:

some text
some more text
. . .
. . .
data {
1 2 3 5 yes 10
2 3 4 5 no  11
}
some text
some text

我想使用正则表达式使用以下过程提取文件的data部分:

proc ExtractData {fileName} {
    set sgd [open $fileName r]
    set sgdContents [read $sgd]
    regexp "data \\{(?.*)\\}" $sgdContents -> data
    puts $data
}

但这会产生以下错误:

couldn't compile regular expression pattern: quantifier operand invalid

我无法弄清楚正则表达式有什么问题。任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

使用此正则表达式

regexp {data \{(.*)\}} $sgdContents wholematch submatch
puts $submatch

wholematch匹配整个模式。在你的情况下它是

data {
1 2 3 5 yes 10
2 3 4 5 no  11
}

submatch仅匹配大括号内的内容,如下所示:

1 2 3 5 yes 10
2 3 4 5 no  11

答案 1 :(得分:0)

以下正则表达式行

regexp "data \\{\\\n(.*?)\\\n\\s*\\}" $sgdContents -> data

原始正则表达式唯一的主要错误是错误放置非贪婪匹配指示符(?),它指示正则表达式引擎在找到第一个匹配后立即停止匹配。

相关问题