user9169344
user9169344

Reputation: 3

How to substitute a string variable in a pattern search

In TCL, I'm trying to pattern search by using regular expression. It's working while using a direct pattern search, but not if I use a variable for the pattern.

For example:

set str "this is actual string to search the pattern"
set pat "the"

regexp {the} $str val
regexp {$pat} $str val1

puts $val;  # it's working
puts $val1; # it's not working, showing error

How to substitute a string variable in a pattern search, I have even used [...] but it's not working

Upvotes: 0

Views: 698

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13272

In this particular case, you can go with

regexp $pat $str val

The braces prevented substitution, so you were matching the literal string "$pat" against your data string.

If you have metacharacters together with a variable substitution in the pattern, as in

if {[regexp -nocase \s$name\s\w+\s\w+\s(\d+) $str val val1]} …

you need to prevent one substitution (backslash substitution) while allowing the other. This can be done with

if {[regexp -nocase [subst -nobackslashes {\s$name\s\w+\s\w+\s(\d+)}] $str val val1]} …

(the switch can be shortened to -nob) but subst can be tricky. It’s easier to get the following right:

if {[regexp -nocase [format {\s%s\s\w+\s\w+\s(\d+)} $name] $str val val1]} …

Note in both cases that braces are used to prevent all substitution, and then subst or format is used to rewrite the desired element in the string.

It’s a good idea to try out the pattern in an interactive shell like

% format {\s%s\s\w+\s\w+\s(\d+)} $name
\sthe\s\w+\s\w+\s(\d+)

That way, one can verify that the pattern looks alright before it is plugged into regexp and tested against data.

Documentation: format, regexp, subst, Syntax of Tcl regular expressions

Upvotes: 1

Related Questions