-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringr.jl
69 lines (52 loc) · 1.88 KB
/
stringr.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Base.Regex(x::Regex) = x
StringOrRegex = Union{AbstractString,Regex}
"""
str_extract(x::AbstractString, pattern::AbstractString)
str_extract(x::Vector{<:AbstractString}, pattern::AbstractString)
"""
function str_extract(x::AbstractString, pattern::StringOrRegex)
r = match(Regex(pattern), x)
r === nothing ? "" : r.match
end
function str_extract(x::Vector{<:AbstractString}, pattern::StringOrRegex)
str_extract.(x, pattern)
end
"""
$(TYPEDSIGNATURES)
"""
function str_extract_all(x::AbstractString, pattern::StringOrRegex)
[x === nothing ? "" : x.match for x in eachmatch(Regex(pattern), x)]
end
str_extract_strip(x::AbstractString, pattern::StringOrRegex) =
strip(str_extract(x, pattern))
"""
str_replace(x::AbstractString, pattern::AbstractString, replacement::AbstractString = "")
"""
function str_replace(x::AbstractString, pattern::StringOrRegex, replacement::AbstractString="")
replace(x, pattern => replacement)
end
function str_replace(x::Vector{<:AbstractString}, pattern::StringOrRegex, replacement::AbstractString="")
str_replace.(x, pattern, replacement)
end
gsub = str_replace
"""
grep(x::Union{AbstractString,Vector{<:AbstractString}},
pattern::AbstractString)::AbstractArray{Int,1}
grepl(x::Vector{<:AbstractString}, pattern::AbstractString)::AbstractArray{Bool,1}
grepl(x::AbstractString, pattern::AbstractString)
"""
function grepl(x::AbstractString, pattern::StringOrRegex)
r = match(Regex(pattern), x)
r === nothing ? false : true
end
function grepl(x::Vector{<:AbstractString}, pattern::StringOrRegex)::AbstractArray{Bool,1}
map(x) do x
grepl(x, pattern)
end
end
function grep(x::Union{AbstractString,Vector{<:AbstractString}},
pattern::StringOrRegex)::AbstractArray{Int,1}
grepl(x, pattern) |> findall
end
export str_extract, str_extract_all, str_extract_strip, str_replace,
grep, grepl, gsub