Txt-Split name from number

From Vectorlab

Jump to: navigation, search


Function to extract the string from an indexed name. For example "Design Layer-3" will return "3" and set the name to "Design Layer". This is useful when you wish to increment the index upon name collision. By Orso B. Schmid


{ Orso *********************************************** }
{ Extracts a number from the end of a string }
{ returns "0" if none found. Used for unique naming }
{ "my name-1 --> returns 1 }
{ "my name-109 --> returns 109 }
{ "my name --> returns 0 }
{ Warning: this removes the occasional "-" separator from string, after extracting the number }
FUNCTION T_SplitNameFromNum(VAR name2check: STRING): INTEGER;
    VAR
        temp_dc : DYNARRAY OF CHAR;
        str : STRING;
        num : REAL;
        
    BEGIN
        temp_dc := name2check;
        
        str := '';
        T_SplitNameFromNum := 0;
        
        { is not already a number }
        IF ValidNumStr(str, num) = FALSE THEN BEGIN
        
            { check if last char is number }
                
            { this seems superfluous, but it is for a weird behavior:
            when you run a script after recompiling, validNumStr returns false, also on a string like "123", which should return true }
            WHILE (Len(temp_dc) > 1) & ValidNumStr(temp_dc[Len(temp_dc)], num) DO BEGIN
                str := Concat(num, str);
                temp_dc := Copy(temp_dc, 1, Len(temp_dc)-1);
            END;
            
            str := Concat(temp_dc, str);
        END;
        
        { the rest becomes a num, if ever }
        IF ValidNumStr(str, num) THEN BEGIN
            T_SplitNameFromNum := num;
            
            { remove the eventual "-" a the end, avoiding creation of empty string }
            WHILE (Len(temp_dc) > 1) & (temp_dc[Len(temp_dc)] = '-') DO
                temp_dc := Copy(temp_dc, 1, Len(temp_dc)-1);
                
            name2check := temp_dc;
        END;
    END;
Personal tools