sing20
sing20

Reputation: 11

split a string and print only numbers from an alphanumeric string

I am a newbee in Tcl. I have a certain string "code_lines_part2021vol32i8mn.txt" and I want to print only the numbers in the format "2021 32 8" How can I do this?

Thanks in advance

Upvotes: 0

Views: 131

Answers (2)

glenn jackman
glenn jackman

Reputation: 246992

I don't have an old Tcl to test with, but try this:

set numbers [regexp -all -inline {\d+} $string]
puts [join $numbers]

Upvotes: 1

Mkn
Mkn

Reputation: 638

You can try this... Idea is to remove all characters other than numbers with regsub command and replace by space :

set your_string "code_lines_part2021vol32i8mn.txt"
regsub -all -nocase {[._a-z]} $your_string { } newstring
lassign $newstring num_1 num_2 num_3
puts "result = $num_1 $num_2 $num_3"
# result = 2021 32 8

This would probably be easier with the regexp command but I haven't figured it out yet.
documentation : regsub, lassign and regexp (if you want try)

Upvotes: 0

Related Questions