繁体   English   中英

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

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

所以基本上我有一些输入的可能性,用户应该只接受数字,否则将提醒用户他的输入不正确。

当我使用回调读出输入时,输入被视为字符串。 现在我想检查字符串(应该包含数字)是否实际上只包含数字,但我没有找到已经实现的解决方案。 我试过了

theString isInteger 

- 字符串永远不会是真的

theString asNumber 

- 忽略字母,但我希望有一个清晰的输出字母是否包括在字符串中

theString isNumber

- 总是假的

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

'1233248539487523' isAllDigits "--> true"

您可以使用正则表达式来检查字符串是否仅包含数字:

theString matchesRegex: '\d+'

或更复杂的正则表达式,以允许可选的符号和小数点:

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

不幸的是,我无法在Cincom Smalltalk上找到消息' isAllDigits '或' matchesRegex '。 但是,您可以做的是从字符串中提取一个单词并使用asNumber将其转换为数字。 因此,如果返回值为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