MEL How-To #80

Back · Previous · Next Maya

How do I extract the numeric part of a unique name; e.g. the value 42 from "pCube42"?

The "match" command is ideal for this. Use the expression pattern "[0-9]+$":

int $number = `match "[0-9]+$" "a1"`;
// Result: 1 //

int $number = `match "[0-9]+$" "pCube42"`;
// Result: 42 //

int $number = `match "[0-9]+$" "blah123"`;
// Result: 123 //

The expression pattern, translated, means "match one or more characters between '0' and '9' at the end of the string."

Note: You'll have to be careful to wrap your assignment to prevent annoying warnings such as:

int $number = `match "[0-9]+$" "noNumber"`;
// Warning: line 1: Converting string "" to an int value of 0. //
// Result: 0 //

You could check first with "gmatch". Note that "gmatch" uses shell-style pattern matching, and not regular expressions. For this binary check use an expression that checks if the last character is numeric - "*[0-9]"; e.g.:

int $number;

string $name = "noNumber";

$number = 0;
if ( `gmatch $name "*[0-9]"` )
{
  $number = `match "[0-9]+$" $name`;
}
// No numeric suffix was found; return default value of 0.
print $number;
// Result: 0 //

string $name2 = "pCube42";

int $number = 0;
if ( `gmatch $name2 "*[0-9]"` )
{
  $number = `match "[0-9]+$" $name2`;
}
print $number;
// Result: 42 //

13 January 2002