Smalltalk: how to check if a string contains only numbers?

so basically I have some input options for the user, where only numbers should be accepted, otherwise the user will be warned that his input was incorrect.

input is considered String when I read it with a callback. now I want to check if the string (which SHOULD contain numbers) ONLY contains numbers, but I have not found a solution already implemented. I tried

theString isInteger 

- never true for string

theString asNumber 

- ignores letters, but I want clear output characters to be entered in the string, and not

theString isNumber

- always false

+4
source share
4 answers

, , :

theString matchesRegex: '\d+'

, :

theString matchesRegex: '-?\\d+(\\.\\d+)?'
+4

Squeak Pharo #isAllDigits, , :

'1233248539487523' isAllDigits "--> true"
+10

, isAllDigits '' matchesRegex ' Cincom Smalltalk. , , asNumber. , 0(zero) , number 0 ( ), string digit/number.

+1

Smalltalks:

(aString detect: [:c| c isDigit not ]) isNil ifTrue: [ "it a number" ]. 
+1

All Articles