Skip to content

Instantly share code, notes, and snippets.

@diegozea
Last active August 29, 2015 14:27
Show Gist options
  • Save diegozea/e689e59f4ed7da1ddf78 to your computer and use it in GitHub Desktop.
Save diegozea/e689e59f4ed7da1ddf78 to your computer and use it in GitHub Desktop.
Perlish wrapper for Julia's match

PerlishMatch

Perlish wrapper for Julia's match: unpacks captures into variables. It could be slower than using match in the Julian way.

Installation

Pkg.clone("https://gist.github.com/e689e59f4ed7da1ddf78.git", "PerlishMatch/src")

Example

julia> using PerlishMatch

julia> uniprot, first_pos, last_pos = m(r"^(\w+)/(\d+)-(\d+)","O83071/192-246")
("O83071","192","246")

julia> uniprot
"O83071"

module PerlishMatch
export m, @m
function tuple_nothing(n::Int)
([nothing for i in 1:n]...)
end
function count_groups(regex::Regex)
opening = 0
closing = 0
for char in regex.pattern
if char == '('
opening += 1
elseif char == ')'
closing += 1
end
end
if opening == closing
return(opening)
else
throw(ErrorException("Different number of '(' and ')'"))
end
end
"""
Perlish wrapper for Julia's match.
Returns a tuple of captures. You can unpack the tuple into variables.
It could be slower than using match in the Julian way.
## Example
```
julia> uniprot, first_pos, last_pos = m(r"^(\w+)/(\d+)-(\d+)","O83071/192-246")
("O83071","192","246")
julia> uniprot
"O83071"
```
"""
function m(regex::Regex, args...)
cap = match(regex, args...)
if cap !== nothing
return(cap.captures...)
else
return(tuple_nothing(count_groups(regex)))
end
end
macro m(exp)
if exp.head == :(=) && exp.args[1].head == :(tuple) && exp.args[2].head == :(call)
@eval begin
cap = $(exp.args[2])
$(exp.args[1]) = cap !== nothing ? (cap.captures...) : tuple_nothing(length($(exp.args[1])))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment