我有一个这种模式的字符串:
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 3And to get each number, you can use lindex:
puts [lindex $numbers 0] # => 2Or 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 # => 3In 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.
更多推荐
发布评论