From c79947cfe207a62afbee0415cc0db33bf3b3fc4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mos=C3=A8=20Giordano?= Date: Tue, 28 Dec 2021 13:03:47 +0100 Subject: [PATCH] Extend `Base.tryparse` (#112) --- NEWS.md | 5 ++++- src/parsing.jl | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index d8caebd5..26901282 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,12 +1,15 @@ # History of Measurements.jl -## v2.7.0 (2021-??-??) +## v2.7.0 (2021-12-28) ### New features * Support hashing of `Measurement` objects ([#103](https://github.com/JuliaPhysics/Measurements.jl/issues/103), [#104](https://github.com/JuliaPhysics/Measurements.jl/pull/104)). +* New method `Base.tryparse(::Type{Measurement}, ::AbstractString)` + ([#110](https://github.com/JuliaPhysics/Measurements.jl/issues/110), + [#112](https://github.com/JuliaPhysics/Measurements.jl/pull/112)). ### Deprecations diff --git a/src/parsing.jl b/src/parsing.jl index 3b3805b8..0488409b 100644 --- a/src/parsing.jl +++ b/src/parsing.jl @@ -83,7 +83,7 @@ julia> measurement("-1234e-1") """ measurement(str::AbstractString) = parse(Measurement{Float64}, str) -function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString} +function Base.tryparse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString} m = match(rxp_error_with_parentheses, str) if m !== nothing # "123(45)e6" val_str::S, val_dec, err_str::S, err_dec_str, expn = m.captures @@ -105,7 +105,7 @@ function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<: val_str, err_str, val_dec, expn = m.captures[1], "0", nothing, nothing else - throw(ArgumentError("cannot parse $(repr(str)) as Measurement{$T}")) + return nothing end end end @@ -127,3 +127,9 @@ function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<: end return measurement(val, err) end + +function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString} + out = tryparse(Measurement{T}, str) + out === nothing && throw(ArgumentError("cannot parse $(repr(str)) as Measurement{$T}")) + return out +end