Questions about string

You can use lookaround operators

julia> c = "9S45M11S"
"9S45M11S"

julia> eachmatch(r"\d+(?=S)", c)
Base.RegexMatchIterator(r"\d+(?=S)", "9S45M11S", false)

They actually match only the numbers:

julia> collect(eachmatch(r"\d+(?=S)", c))
2-element Vector{RegexMatch}:
 RegexMatch("9")
 RegexMatch("11")

Now, I would have expected this to work, but sadly, and confusingly, it doesn’t:

julia> parse.(Int, eachmatch(r"\d+(?=S)", c))
ERROR: MethodError: no method matching parse(::Type{Int64}, ::RegexMatch)

Instead, it seems I must dig around in the internals of the match object, for example like this:

julia> [parse(Int, m.match) for m in eachmatch(r"\d+(?=S)", c)]
2-element Vector{Int64}:
  9
 11

This should be very efficient, but it’s not nice to have to dig into the internal match field of the object, and it always seemed to me like an outlier in the language.

3 Likes