0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, that's working but i suppose to use with metacharacters to search the lines from another file. here the statement is if {[regexp -nocase \s$name\s\w+\s\w+\s(\d+) $str val val1]}. previously i mentioned as if {[regexp -nocase {\s$name\s\w+\s\w+\s(\d+)} $str val val1]}. Finally your solution is working but not with metacharacters for this condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.