简体   繁体   English

tcl:正则表达式匹配在字符串末尾

[英]tcl: regexp match subsring at the end of string

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在str1的末尾匹配"{k}"

regexp .*\.\{k\}\.$ $str1 

but I got 0 !! 但是我有0! in fact I use regsub to test the regexp 实际上,我使用regsub来测试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}. 在您的代码中,正则regexp仅返回值1,而不返回0。当您想匹配最后出现的.{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. 使用regsub ,您应该使用向后引用来捕获第一个组,以便可以正确地替换它。

puts [regsub "(.*)(\.{k}\.)" $str1 "\\1"] 

Output : 输出:

st1.st2.{k}.st3.{k}.st4

What is wrong with regsub {.*\\.\\{k\\}\\.$} $str {} ? 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. 好的,模式.*\\.\\{k\\}\\.$将匹配整个字符串,并且您将其替换为空字符串,这就是为什么得到空结果的原因。

Reference : Noncapturing Subpatterns 参考: 非捕获子模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM