一直在搜寻互联网上的信息,试过了isnumeric
,但只适用于AbstractChar
。如果可能的话,我宁愿不使用tryparse
,但如果这是唯一的解决方案,那就这样吧... 如果是这样,为什么还没有实现一个检查字符串是否为数字的函数呢?
我找到的最快解决方案是使用建议的tryparse
方法。
function check_str2(a)
return tryparse(Float64, a) !== nothing
end
与正则表达式的40ns相比,它平均为20ns。
没有办法在不进行转换的情况下检查字符串是否有效,主要原因是在性能关键的地方实际上没有多少强制性的用例需要这样做。 在大多数情况下,您希望知道某些东西是否可以解析为数字以将其用作数字,而在罕见的情况下,额外的几个纳秒可能并不重要。
@benchmark
。我正在使用julia 1.1.1版本。 - Oscar Smithcheck_str2("60.0xxx")
返回false
。 (我很惊讶它曾经返回true
)。 - kmsquireParsers.jl
包中的 Parsers.tryparse
确实具有 @PrzemyslawSzufel 指出的行为。然而,在 Julia 的 Base
中,tryparse
并没有相同的行为(即它可以工作),并且实际上比下面的 check_str
更快。我编辑了这个解决方案,使用了 Base
版本。 - kmsquireBase.tryparse
仍然比我的答案慢2倍。因此,正则表达式是这里的最佳选择。 - Przemyslaw Szufel通常你可以使用正则表达式来检查一个字符串是否为数字:
julia> re = r"^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$";
julia> occursin(re,"123.")
true
julia> occursin(re,"123.0")
true
julia> occursin(re,"123.012")
true
julia> occursin(re,"123")
true
julia> occursin(re,"ab")
false
julia> occursin(re,"ab123.1")
false
julia> occursin(re,"123.1e")
false
function check_str(a)
try
parse(Float64,a)
true
catch
false
end
end
以下是基准测试结果。请注意,正则表达式大约快了 200 倍(如果我们还决定查找指数部分,则增加量将更小),而且不会分配内存。
julia> using BenchmarkTools
julia> @btime check_str("60.0a")
15.359 μs (18 allocations: 816 bytes)
false
julia> @btime occursin($re,"60.0a")
67.023 ns (0 allocations: 0 bytes)
false
当成功解析String
时,速度差距要小得多:
julia> @btime check_str("60.0")
298.833 ns (0 allocations: 0 bytes)
true
julia> @btime occursin($re,"60.0")
58.865 ns (0 allocations: 0 bytes)
true
tryparse
吗? - Oscar Smithisa(tryparse(Float64,"StringNumber"), Number) # true | false
正如OP在评论中所建议的,他们只需要检查整数,你仍然可以使用isnumeric
(或者可能更好地使用isdigit
):
isintstring(str) = all(isdigit, str)
这个方法似乎比其他答案都要快。在我的电脑上,它的基准测试速度大约比 tryparse
解决方案快2倍。
1.0e2
是数字吗?6.2f22
是数字吗?0x02
呢?还有0b100101
和0xdead_beef.cap23
呢? - mbaumanisintstring(str) = !isnothing(match(r"^\d*$", str))
,或者类似的方法。但是它会更慢。我猜你认为tryparse
很麻烦,因为你没有真正意识到这是如何完成的,从概念上讲。(编辑:哎呀,完全错过了下面的实际回复。) - DNF