如何检查字符串是否为数字Julia

时间:2019-06-12 08:42:38

标签: string numbers julia numeric

曾经搜寻互联网试图弄清楚这一点。尝试过['Jack', 'Steve',...] ,但仅适用于isnumeric。如果可能的话,我宁愿不必使用AbstractChar,但是如果那是唯一的解决方案,那么……如果是,为什么还没有实现用于检查字符串是否为数字的函数呢? / p>

4 个答案:

答案 0 :(得分:1)

通常使用正则表达式检查字符串是否为数字:

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

注意:我使用了Regular expression for floating point numbers中的正则表达式,如果您只是想使用整数部分或包含指数,那么也很容易找到这样的现成正则表达式。

编辑:基准测试。

让我们考虑以下函数来检查字符串是否为数字:

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

答案 1 :(得分:1)

这对我有用:

isa(tryparse(Float64,"StringNumber"), Number)    # true | false

答案 2 :(得分:0)

正如 OP 在评论中建议的那样,他们只需要检查整数,您仍然可以使用 isnumeric(或者使用 isdigit 可能更好):

isintstring(str) = all(isdigit(c) for c in str)

这似乎比这里的其他答案更快。在我的机器上,它的基准测试时间约为 37/38 ns,而 tryparse 解决方案的基准测试时间约为 64/65 ns。

答案 3 :(得分:-2)

我发现最快的解决方案是推荐使用tryparse。

function check_str2(a)
    return Parsers.tryparse(Float64, a)!==nothing
end

平均为20ns,而正则表达式为40ns。

无法不经过转换就检查字符串是否有效为int的主要原因是,在性能很重要的地方,并没有太多令人信服的用例。在大多数地方,您想知道是否可以将某事物解析为数字以将其用作数字,并且在极少数情况下,多余的ns可能无关紧要。

相关问题