Reputation: 175
I wanted to replace a character in a string, based on pattern matching. The variable value of temp
is given by the user and may or may not have preceding "m".
But in case it does have a preceeding m
, I want to replace the character m
with "-"
(minus sign).
so if the value of temp
is "m40"
, then temp1
should look like "-40"
Here is what i am tried, but it doesn't work well:
set temp "m40c"
if {regexp ^m $temp match} {
regsub m $temp "-" $temp1
puts $temp1
}
Upvotes: 0
Views: 4078
Reputation: 385
or in one line,
set temp [regsub {^\s*m} $temp "-"]
if you want to replace M or m ( case insensitive )
set temp [regsub -nocase {^\s*m} $temp "-"]
Upvotes: 0
Reputation: 10602
regexp, in the abov example is redundant. regsub will replace, if it finds a match. It doesn't throw any error otherwise.
% regsub "^m" $temp "-" temp1
1
% set temp1
-40c
% set temp "xm40c"
xm40c
% regsub "^m" $temp "-" temp2
0
% set temp2
xm40c
%
So, something like this may be useful:
puts "Original value: $temp"
if {[regsub "^m" $temp "-" temp]} {
puts "Updated value: $temp"
}
Upvotes: 2
Reputation: 16428
You can straightaway use the regsub
command.
% set temp "m40c"
m40c
% regsub m $temp - result
1
% set result
-40c
% set temp "40c"
40c
% regsub m $temp - result2
0
% set result2
40c
%
Upvotes: 1
Reputation: 175
I did tried this code and it works for me ... just missed the [] brackets around regexp.
set temp "m40c"
if {[regexp ^m $temp match]} {
regsub m $temp "-" temp1
puts $temp1
}
Upvotes: 1