从TCL中的字符串中提取整数(Extracting integer from a string in TCL)

编程入门 行业动态 更新时间:2024-10-25 08:24:04
从TCL中的字符串中提取整数(Extracting integer from a string in TCL)

我有一个这种模式的字符串:

2(some_substring) -> 3(some_other_substring)

现在这些数字可以是任何东西。

我认为这个答案可以解决问题。 但它给出了一个变量中的所有整数。 我希望它们处于不同的变量中,以便我可以分析它们。 我们能分开吗? 但拆分会导致问题:

如果数字不是单个数字,那么分割将是错误的。

还有别的办法吗?

I have a string in this pattern:

2(some_substring) -> 3(some_other_substring)

Now these number can be anything.

I think this answer would solve the problem. But it gives all the integers in one variable. I want them to be in different variables, so that I can analyze them. Can we split it? But Splitting would cause problem:

If the the numbers are not single-digit, then the splitting will be erroneous.

Is there any other way?

最满意答案

您可以使用以下变体:您可以将所有数字字符提取到列表中,而不是删除非数字字符:

set text {2(some_substring) -> 3(some_other_substring)} set numbers [regexp -all -inline -- {[0-9]+} $text] puts $numbers # => 2 3

要获得每个数字,您可以使用lindex :

puts [lindex $numbers 0] # => 2

或者在8.5及更高版本中,您可以使用lassign将它们分配给特定的变量名称:

lassign $numbers first second puts $first # => 2 puts $second # => 3

在regexp -all -inline -- {[0-9]+} $text , -all提取所有匹配项, -inline将匹配项放入列表中, --结束选项, [0-9]+匹配至少一个整数。

You can use a variation of this: instead of removing the non-digit characters, you can extract all digit characters into a list:

set text {2(some_substring) -> 3(some_other_substring)} set numbers [regexp -all -inline -- {[0-9]+} $text] puts $numbers # => 2 3

And to get each number, you can use lindex:

puts [lindex $numbers 0] # => 2

Or in versions 8.5 and later, you can use lassign to assign them to specific variable names:

lassign $numbers first second puts $first # => 2 puts $second # => 3

In regexp -all -inline -- {[0-9]+} $text, -all extract all the matches, -inline puts the matches into a list, -- ends the options, [0-9]+ matches at least one integer.

更多推荐

本文发布于:2023-08-07 16:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   TCL   string   integer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!