Possible Duplicate:
How to use a variable in regexp expression (TCL/Expect)
I want help in passing varibles to a regexp.
Suppose my code is
set line "MPID:22 condition:AIS"
set id 22
if {[regexp {MPID:$id} $line]} {
puts "inside if"
}
This regexp doesn't work. If I change regexp to
{[regexp {MPID:22} $line]}
it works.
Can someone provide a solution for this.
If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() . In the above code, we have passed the removeStr variable as an argument to the new RegExp() constructor method.
tcl Regular Expressions SubstitutionThe regsub command is used for regular expression matching and substitution. set mydata {The yellow dog has the blues.} # create a new string; only the first match is replaced. set newdata [regsub {(yellow|blue)} $mydata green] puts $newdata The green dog has the blues.
Solution: As we know, any number of a's means a* any number of b's means b*, any number of c's means c*. Since as given in problem statement, b's appear after a's and c's appear after b's. So the regular expression could be: R = a* b* c*
Instead of {MPID:$id}
you want to use "MPID:$id"
:
if {[regexp "MPID:$id" $line]} {
puts "inside if"
}
The {...}
are used by tcl to group parts of an expression together but prevent variable expansion.
If you want variable expansion you should use "..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With