如果其中的元素可以变成 int 或 double,是否可以检查字符串数组?

Is it possible to check an array of strings, if an element within it could be turned into an int or double?

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

使用这样的正则表达式-?\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 函数,因此如果字符串无法转换为浮点数或整数,则它将 return false.

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

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

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

please visit this site to see the regex in action