Reputation: 1778
Hi let say i have couple of name : orange12 , blue124 , red909
, and i want to grab the index number , in this case : 12 , 124 and 909. Ussually , i can use 'string range first last' to extract the substring .And to get the first and last i will use 'string len orange' and 'string len orange12'. Now I'm looking another way to do it.
As comparison , in python , i can do something like :
'orange12'.split('orange')[1]
'blue124'.split('blue')[1]
'red909'.split('red')[1]
How can i do something like that in tcl ? I tried the 'split' in tcl , but seems complicated and couldn't make it works. In tcl how can i split by a word (not character) ?
Thanks
Upvotes: 1
Views: 4170
Reputation: 1778
i finally find the best answer for my own question, i'd like to share here :
set name orange12345
[scan $name [scan $name {%[a-zA-Z]}]%d ]
#12345
where i can do this without have to know the word 'orange' from 'orange12' . so the source name can be any random name in format like : ANYNAMEanynumber. For example , the name like 'mywonderfulworld2345612'.
Upvotes: 0
Reputation: 279
It depends on exactly what string format you expect.
If it is a known word (without digits), e.g. 'orange', followed by some digits, you may remove the word:
% string map {orange ""} orange12
12
% string map {blue ""} blue124
124
% string map {red ""} red909
909
If it is only known that it is a word followed by digits, you may try a regular expression.
% regexp {\d+} orange12 index
1
% puts $index
12
Anyway, note that the digits are still represented as a string. If it starts with a zero it will be interpreted as an octal, when converted to numeric format, which may lead to unexpected results.
One option is passing it through scan
:
% regexp {\d+} orange012 index
1
% puts $index
012
% expr 1*$index
10
% set index [scan $index %d]
12
% expr 1*$index
12
Edit: used one of Peter's suggestions
Upvotes: 2
Reputation: 13272
The other answers show you the best ways to solve your problem in Tcl, but to answer the question you posed, here's the equivalent code in Tcl:
package require textutil
lindex [textutil::splitx orange12 orange] 1
lindex [textutil::splitx blue124 blue] 1
lindex [textutil::splitx red909 red] 1
The textutil
package is a part of Tcllib
, the Tcl companion library. The splitx
command is an extending replacement for the core command split
: splitx
takes a regular expression instead of a character set to determine where to split the string argument.
Documentation: lindex, textutil package
Upvotes: 1
Reputation: 137667
Sometimes, scan
is the most useful tool. It's often overlooked too:
scan "green012" {%[a-z]%d} word num
# $word is now “green”
# $num is now “12”
Upvotes: 6