XYZ_Linux
XYZ_Linux

Reputation: 3597

How to match a Variable in a regexp?

I am trying to write a Tcl script in which I need to match a variable in a regular expression. For instance, file has some lines of code containing 'major'. Out of all these lines I need to identify one particular line:

major("major",0x32)

I m using variable p1 for 'major' (set p1 major)

How can I write a regexp using variable p1 ($p1) to capture that particular line?

Upvotes: 1

Views: 6174

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Use a String Match

If you just want to know whether a single line matches, you can test for string match rather than a regular expression. This is often faster and less finicky. For example:

set fh [open /tmp/foo]
set lines [read $fh]
close $fh

set p1 major

set lines [split $lines "\n"]
foreach line $lines {
    if {[string match *$p1* $line]} {set match $line}
}
puts $match

Note that this will store the entire line in match, and not just the search pattern. This is probably what you want, but your mileage may vary.

Upvotes: 1

Andrew Cheong
Andrew Cheong

Reputation: 30273

regexp -- "$p1\\(\"$p1\",0x32\\)" $line match

In tclsh:

% set line {major("major",0x32)}
major("major",0x32)
% set p1 major
major
% regexp -- "$p1\\(\"$p1\",0x32\\)" $line match
1
% puts $match
major("major",0x32)

Upvotes: 2

Related Questions