Tcl - 将regexp结果保存到变量中

时间:2014-09-26 04:25:25

标签: regex tcl

我想做以下事情:

获取<body>标记并存储在变量中。 <body>标记每次都可能不是字符串<body>,而是"\<body bgcolor="somehex" blah="blah"\>

我想通过正则表达式捕获整个body标签并将其保存到变量中。

2 个答案:

答案 0 :(得分:2)

我将假设反斜杠并不意味着在实际的html字符串中。

regexp -- {body[^>]*} $html bodytag
# -> 1
set bodytag
# -> body bgcolor="somehex" blah="blah"

文档:regexpsetTcl regular expression syntax

答案 1 :(得分:0)

您可以尝试如下。

set html {<body bgcolor="somehex" blah="blah"\>}

#The first sub-match will hold the tag content and will be saved in the variable 'body_content'
#The variable 'all' will hold the whole content including the body tag itself

# The flag '-nocase' causes case insensitive match
if {  [ regexp -nocase {<body\s+(.*)\\>} $html all body_content]  } { 
    puts $body_content
} else { 
    puts "No match found"
}

请注意使用\s+\\,其中前一个与空格匹配,之后一个人负责关闭正文标记。如果您想进一步操作,可以自定义regexp