Created
September 2, 2018 12:21
-
-
Save drsimonj/0646565951204538d72f27a672d8ed60 to your computer and use it in GitHub Desktop.
regex - recursive EBNF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## BASE FUNCTION | |
base <- function(obj) { | |
UseMethod("base") | |
} | |
base.default <- function(obj) { | |
as.character(obj) | |
} | |
base.regex <- function(obj) { | |
paste0("(", obj, ")") | |
} | |
base("a") | |
base(1) | |
x <- "a" | |
class(x) <- c("regex", class(x)) | |
base(x) | |
# QUANTIFIED FUNCTION (FACTOR) | |
quantified <- function(base, quantifier_min = 1, quantifier_max = 1) { | |
paste0(base, "{", quantifier_min, ",", quantifier_max, "}") | |
} | |
quantified(base("a")) | |
quantified(base(x)) | |
# TERM FUNCTION | |
term <- function(...) { | |
quantified <- c(...) | |
paste0(quantified, collapse = "") | |
} | |
term(quantified(base("a")), quantified(base("b"))) | |
term(c(quantified(base("a")), quantified(base("b")))) | |
term(c(quantified(base("a")), quantified(base("b"))), quantified(base(x))) | |
# REGEX FUNCTION | |
regex <- function(term, reg) { | |
if (!missing(reg)) { | |
term <- paste(term, base(reg), sep = "|") | |
} | |
class(term) <- c("regex", class(term)) | |
term | |
} | |
regex(term(quantified(base("a")), quantified(base("b")))) | |
y <- regex(term(quantified(base("a")), quantified(base("b")))) | |
test_regex <- regex( | |
term(quantified(base("x")), quantified(base("y"))), | |
y | |
) | |
regex | |
regex( | |
term(quantified(base(1))), | |
test_regex | |
) | |
stringr::str_extract_all("thda jd skj xy", test_regex) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A more advanced example (truer to the grammar):