I trying to match a substring occurs many times in string
str1 = st1.st2.{k}.st3.{k}.st4.{k}.
str2 = st1.st2.{k}.st3.{k}.st4.
I use regexp to match "{k}"
at the end of str1:
regexp .*\.\{k\}\.$ $str1
but I got 0 !! in fact I use regsub to test the regexp
regsub {.*\.\{k\}\.$} $str {}
result ==> empty
if the pattern is matched, the matched string will be removed !! what missing in regexp expression ?
In your code, the regexp
is returning the value 1 only, not 0. When you want to match the last occurrence of .{k}.
, you have to go ahead with sub-matches to get what you want.
set str1 st1.st2.{k}.st3.{k}.st4.{k}.
puts [regexp ".*(\.{k}\.)" $str1 whole last]
puts $last
Output :
1
.{k}.
The $
sign is not mandatory to specify the end of line as we simply want to match the last occurrence.
With the regsub
, you should be using the back-reference to capture the 1st group, so that it can be replaced correctly.
puts [regsub "(.*)(\.{k}\.)" $str1 "\\1"]
Output :
st1.st2.{k}.st3.{k}.st4
What is wrong with regsub {.*\\.\\{k\\}\\.$} $str {}
?
Well, the pattern .*\\.\\{k\\}\\.$
will match the whole string and you are replacing it with empty string, which is why you are getting the empty result.
Reference : Noncapturing Subpatterns
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.