Skip to content

Commit

Permalink
add convert(::Type{Regex}, ::Union{AbstractString,AbstractChar})
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed May 10, 2019
1 parent 829a4a6 commit 8f50fe4
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
30 changes: 29 additions & 1 deletion base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ function hash(r::Regex, h::UInt)
h = hash(r.match_options, h)
end

## String operations ##
## string operations ##

"""
*(s::Regex, t::Union{Regex,AbstractString,AbstractChar}) -> Regex
Expand Down Expand Up @@ -645,3 +645,31 @@ RegexMatch("Test Test ")
```
"""
^(r::Regex, i::Integer) = Regex(string("(?:", r.pattern, "){$i}"), r.compile_options, r.match_options)

## conversion from strings/chars ##

"""
convert(::Type{Regex}, x::AbstractChar)
convert(::Type{Regex}, x::AbstractString)
Create a `Regex` which matches `x` exactly. This means that special characters are
not interpreted as having special meaning.
Multiplication can also be used in order to create a regex with specific flags.
!!! compat "Julia 1.3"
This method requires at least Julia 1.3.
# Examples
```jldoctest
julia> match(convert(Regex, '('), "(").match
"("
julia> match(convert(Regex, ".*"), "abc") == nothing
true
julia> match(convert(Regex, ".*"), ".*")
RegexMatch(".*")
```
"""
convert(::Type{Regex}, s::Union{AbstractString,AbstractChar}) = Regex(wrap_string(s, zero(UInt32)))
19 changes: 19 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,25 @@
@test r"this|that"^2 == r"(?:this|that){2}"
end

@testset "convert from strings/chars" begin
r = convert(Regex, 'a')
@test r == r"\Qa\E" # these tests can change if the implementation changes
@test match(r, "a").match == "a"
r = convert(Regex, '\\')
@test r == r"\Q\\E"
@test match(r, "\\").match == "\\"
r = convert(Regex, '(')
@test r == r"\Q(\E"
@test match(r, "(").match == "("

r = convert(Regex, "a\\b(c")
@test r == r"\Qa\b(c\E"
@test match(r, "a\\b(c").match == "a\\b(c"
r = convert(Regex, "a\\E\\Qz")
@test r == r"\Qa\\E\QE\Qz\E"
@test match(r, "a\\E\\Qz") != nothing
end

# Test that PCRE throws the correct kind of error
# TODO: Uncomment this once the corresponding change has propagated to CI
#@test_throws ErrorException Base.PCRE.info(C_NULL, Base.PCRE.INFO_NAMECOUNT, UInt32)
Expand Down

0 comments on commit 8f50fe4

Please sign in to comment.