【问题标题】:Is there any way to check character input from a readline is a number?有什么方法可以检查从 readline 输入的字符是数字吗?
【发布时间】:2017-03-16 15:05:05
【问题描述】:

我想问一下是否有办法检查readline() 的结果是否为数字。

因为我需要对这些输入进行数学运算,所以除了数字和“。”之外的任何字符。会破坏程序。

我必须逐个字母地处理输入字符串来检查每个字符吗?还是有一些优雅的方法来做到这一点?

【问题讨论】:

  • readline() 的值是“长度为 1 的字符向量”(引用 ?readline)。你为什么不把它包装在as.numeric() 中,让你的程序对NA 输入健壮?
  • @apom 使用 as.numeric 的问题在于它默认会更改输入,例如如果输入是“2,8”而不是“2.8”,则结果将是数字 2

标签: r regex readline numeric


【解决方案1】:

函数readline() 总是返回一个字符串。您可以通过两种方式处理此问题:

  • as.numeric() 使用蛮力:这将返回任何无法转换为数字的NA。然后,您可以与 is.na() 联系,看看这是否有效。
  • 使用正则表达式。使用grepl(),您可以为向量的每个元素获得一个TRUE/FALSE 值,指示是否找到了某个字符。

尝试以下方法:

x <- readline("give a number: ")
if(grepl("[^[:digit:]\\.-]",x)) stop("This is not a number") else "Hooray"

工作如下:

> x <- readline("give a number: ")
give a number: -23.48
> if(grepl("[^[:digit:]\\.-]",x)) stop("This is not a number") else "Hooray"
[1] "Hooray"
> x <- readline("give a number: ")
give a number: -25.645)
> if(grepl("[^[:digit:]\\.-]",x)) stop("This is not a number") else "Hooray"
Error: This is not a number

如果你想彻底检查某些东西是否被格式化为数字(包括科学记数法),这是一个经典的正则表达式来测试它:

"ˆ[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$"

那就是:

x <- readline("give a number: ")
isnumber <- grepl("ˆ[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$",x)
if(!isnumber) stop("X is not a number") else "Hooray"

【讨论】:

  • 正则表达式有一些潜在的漏洞; "13.234.2342" 作为测试用例怎么样...? +23 是合法号码吗? 1.0e23...怎么样?
  • @BenBolker 第二个正则表达式解决了所有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多