MEL How-To #80 | ||
| ||
How do I extract the numeric part of a unique name; e.g. the value 42 from "pCube42"?The " 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 "
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 //
| ||
Copyright ©2005 by Bryan Ewert, maya@ewertb.com Maya is a Registered Trademark of Alias |