Notifications
Clear all

[Closed] Find out if single char string is number

Hey guys!

I’m working on a function that will split of the number-suffix of a string.
i.e. “hello01” should be split into “hello” as a string and “01” as a number.

My current approach is to cut of the last character of the string until I hit a letter.
For this I need a reliable way to detect numbers.
Just using myString[1] as integer isn’t reliable because “s” as integer will return 0.

Now I want to try using regular expressions, but I can’t find anything in the help on how to actually use them. There’s a doc that explains regexp, but no function to compare with them.

Can you help?

Cheers!
-Sascha

6 Replies
1 Reply
(@bobo)
Joined: 1 year ago

Posts: 0

Here is a quick a dirty workaround:

fn SplitSuffix str =
(
	local result = #("",str)
	for i = str.count to 1 by -1 do if findString "0123456789" str[i] == undefined do
	(
		result = #(substring str 1 i, substring str (i+1) -1)
		exit
	)	
	result
)

SplitSuffix "Bobo1Land2_42"
--> #("Bobo1Land2_", "42")

SplitSuffix "Bobo" 
--> #("Bobo", "")

SplitSuffix "2012"
--> #("", "2012")

Nice idea to use the numbers as the string to search in!

Anyway, I found some dotNet regExp stuff on here and use that now:

    local sMainPart = myString
    local sNumberPart = ""
    				
    while sMainPart.count > 0 and ((dotNetClass System.Text.RegularExpressions.Regex").match sMainPart[sMainPart.count] "\d").Success do
   (--while last character is a number
    	sNumberPart = sMainPart[sMainPart.count] + sNumberPart
    	sMainPart = substring sMainPart 1 (sMainPart.count - 1)
   )
    

Seems to work.

your function works very slow and causes huge memory leaking…
try this one:


fn splitString str = 
(
t = trimRight str "0123456789"
#(t, substring str (t.count+1) -1)
) 

it works 200 times faster

From the doc about the trimRight function:
“The following string parsing methods were first introduced in gmax 1.0 and are available in MAXScript since 3ds Max 5.”

Don’t you love maxscript with all the secret features, hidden in the darkest corners of the doc – waiting to be discovered, but not any earlier than you find yourself a jungle-guide who knows this mess by heart…

It really is blinding fast – will implement that asap.
Thanks a ton!

if all you need returned from your function is a boolean value, simplifying denisT’s method to

fn splitString str =  (trimLeft str "0123456789").count == 0

offers a further 50% improvement by my calculations. Note that i switched to using the trimLeft function which turns out to be a bit faster

Nah, I need to actually split it off.
I will later increment the number part if necessary to ensure unique names when adding user defined names to a list.