简体   繁体   English

Smalltalk:如何检查一个只包含数字的字符串?

[英]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 . 不幸的是,我无法在Cincom Smalltalk上找到消息' isAllDigits '或' matchesRegex '。 However, what you could do is extract a word from the string and convert it to a number using asNumber . 但是,您可以做的是从字符串中提取一个单词并使用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 . 因此,如果返回值为0(zero)则表示该number实际为0 (可以使用附加条件检查)或string不包含digit/number

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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