Any way to check if a string contains a decimal number and convert it?

I'm coding a cross-assembler (for an architecture that doesn't exist in hardware yet) in Rust (which may or may not be a good idea) and at the moment I'm trying to implement a function that will check if the beginning of the given string (which is borrowed) contains a valid immediate value. For reference, an immediate can be a binary, decimal, or hexadecimal number (prefixed with #%, #, and #$ respectively) or a zero-terminated string (surrounded by quotes, the zero is added in the final binary).

My only issue is that I am having trouble checking if the number is actually valid, specifically decimal numbers. For pretty much all of the numbers I will have to check how long the numbers are. After that, verifying binary and hex numbers would be as easy as using .matches() or a regex library. Decimal numbers would not be so easy however. For decimal numbers, I would have to convert the relevant part of the string to an unsigned integer and check the value. However, I cannot find any way to do that in the standard library. Is there any way at all to do this?

Can you use a regex to extract the bit of text that looks like a binary/decimal/hexadecimal number, then use the relevant integer type's from_str_radix() method to parse it? If the number is too big to fit into the integer type then you'll get an error and can handle it appropriately.

1 Like

I actually never found from_str_radix() when looking through the standard library. I'll have to give it a look.