Is there a way to keep the delimiter in split function, as a separate element?

I guess you’re looking for a Base Julia way to do this, but in case you just want to get your problem solved, you can do it with lookaheads and lookbehinds. I have a package ReadableRegex which makes this a bit nicer to read:

using ReadableRegex

function split_keeping_splitter(string, splitter)
    r = Regex(
        either(
            look_for("", before = splitter),
            look_for("", after = splitter)
        )
    )
    split(string, r)
end

split_keeping_splitter("123.456.789", ".")
5-element Vector{SubString{String}}:
 "123"
 "."
 "456"
 "."
 "789"

The regex being constructed for the “.” version would be r"(?:(?:(?<=\.)(?:))|(?:(?:)(?=\.)))" so I can’t recommend constructing that yourself :wink:

5 Likes