简体   繁体   中英

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

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

the input is considered a String when I read it out using a callback. now I want to check whether the string(which SHOULD contain numbers) actually DOES ONLY contain numbers, but I didnt find a solution implemented already. i tried

theString isInteger 

-is never true for the string

theString asNumber 

- ignores letters, but I want to have a clear output wether letters are included in the string or not

theString isNumber

- always false

在Squeak和Pharo中,您有#isAllDigits消息,它可以完全满足您的需求:

'1233248539487523' isAllDigits "--> true"

You can use a regular expression to check that the string contains only numbers:

theString matchesRegex: '\d+'

or a more complex regular expression to also allow an optional sign and decimal point:

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

Unfortunately, I could not locate messages ' isAllDigits ' or ' matchesRegex 'on Cincom Smalltalk . However, what you could do is extract a word from the string and convert it to a number using asNumber . So, if the returned value is 0(zero) it means that either the number is actually a 0 (which could e checked with an additional condition) or string did not contain a digit/number .

这应该适用于许多Smalltalks方言:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM