2

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can i use: set no1 [lindex $numbers 0] set no2 [lindex $numbers 1] ?
yep that worked.. i can set them like that too. Thanks
1

To extend Jerry's answer, in case digits can appear within the parentheses, a regular expression to only extract digits that are immediately followed by an open parenthesis is: {\d+(=\()}

% set text {2(some_6substring) -> 3(some_other_5substring)}
2(some_6substring) -> 3(some_other_5substring)
% lassign [regexp -all -inline {\d+(?=\()} $text] first second
% set first
2
% set second
3

This assumes that you don't have nested parentheses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.