【问题标题】:Is it possible to check an array of strings, if an element within it could be turned into an int or double?是否可以检查字符串数组,如果其中的元素可以转换为 int 或 double?
【发布时间】:2020-03-27 08:03:42
【问题描述】:

我想知道您是否可以检查字符串数组中的元素,看看它们是否可以解析为 int 或 double?我知道你可以尝试解析元素并处理抛出的异常,但还有其他方法吗?

【问题讨论】:

标签: java arrays string int double


【解决方案1】:

使用像这样的正则表达式-?\d+(.\d+)?

-?     --> optional negative symbol
\d+    --> indicates a sequence of one or more numbers
.?     --> optional decimal (for floats)
(\d+)? --> optional digits following the decimal

要匹配的命令类似于str.matches("-?\\d+(.\\d+)?");,我只需使用增强的 for 循环遍历它。 String.matches() 是一个内置的 boolean 函数,所以如果字符串不能转换为浮点数或整数,那么它将返回 false

\\ 只是为了转义文字 \ 字符。

如果您不希望该模式与 fewkjnf12.345r52v 的一部分相匹配,那么只需添加一个克拉来表示 float/int 的开头不应包含字符串,并在末尾添加一个美元符号确保后面没有任何内容的字符串

^-?\d+(.\d+)?$

please visit this site to see the regex in action

【讨论】:

  • 谢谢,这可能是最好的方法,感谢您的回答。
猜你喜欢
  • 2022-10-15
  • 1970-01-01
  • 2017-09-12
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 2021-08-04
  • 2010-12-28
相关资源
最近更新 更多