Consideration
Consideration

Reputation: 342

TCL: How to remove all letters/numbers from a string?

I am using tcl programming language and trying to remove all the letters or numbers from a string. From this example, I know a general way to remove all the letters from a string (e.x. set s abcdefg0123456) is

set new_s [string trim $s "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXXYZ"]

If I want to remove all numbers from a string in general, I can do

set new_s [string trim $s "0123456789"]

Is there a more straightforward way to remove all letters/numbers?

I also notice if I want to remove a portion of numbers (e.x. 012) instead of all numbers, the following does NOT work.

set new_s [string trim $s "012"]

Can someone explain why?

Upvotes: 2

Views: 1451

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137757

To answer your other question: string trim (and string trimleft and string trimright as “half” versions) removes a set of characters from the ends of a string (and returns the new string; it's a pure functional operation). It doesn't do anything to the interior of the string. It doesn't know anything about patterns. The default set of characters removed is “whitespace” (spaces, newlines, tabs, etc.)

When you do:

set new_s [string trim $s "012"]

You are setting the removal set to 0, 1 and 2, but it is still only the ends that get removed. Thus it will leave x012101210y entirely alone, but turn 012101210 into the empty string.

Upvotes: 1

Shawn
Shawn

Reputation: 52579

Use regular expressions:

set s abcdefg0123456
regsub -all {\d+} $s {} new_s ;# Remove all digits
regsub -all {[[:alpha:]]+} $s {} new_s ;# Remove all letters

Upvotes: 5

Related Questions