user1660886
user1660886

Reputation: 79

Tcl - Save regexp result into a variable

I want to do the following:

Take the <body> tag and store in a variable. <body> tag may not be string <body>every time, but "\<body bgcolor="somehex" blah="blah"\>

I want to capture the entire body tag via regex and save it into a variable.

Upvotes: 0

Views: 959

Answers (2)

Dinesh
Dinesh

Reputation: 16428

You can try like as below.

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"
}

Please note the use of \s+ and \\ where the former one matches the spaces and later one took care of the closing body tag. You can customize the regexp if you would like to manipulate any further.

Upvotes: 1

Peter Lewerin
Peter Lewerin

Reputation: 13252

I'm going to assume the backslashes weren't meant to be in the actual html string.

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

Documentation: regexp, set, Tcl regular expression syntax

Upvotes: 2

Related Questions