Home > Back-end >  split a string and print only numbers from an alphanumeric string
split a string and print only numbers from an alphanumeric string

Time:11-16

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

CodePudding user response:

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

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

CodePudding user response:

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)

  • Related