-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathescape.R
92 lines (78 loc) · 2.3 KB
/
escape.R
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#' @include utils.R
NULL
#' Escape characters for a regex
#'
#' @param x Object to escape.
#' @export
escape <- function(x) UseMethod("escape")
#' @describeIn escape Objects are simply passed through unchanged.
#' @export
escape.regex <- function(x) x
#' @describeIn escape Objects are surrounded by braces.
#' @export
escape.character_class <- function(x) {
p("[", x, "]")
}
#' @describeIn escape Objects are properly escaped for regular expressions.
#' @export
escape.character <- function(x) {
chars <-
c("*",
".",
"?",
"^",
"+",
"$",
"|",
"(",
")",
"[",
"]",
"{",
"}",
"\\"
)
regex(gsub(paste0("([\\", paste0(collapse = "\\", chars), "])"), "\\\\\\1", x, perl = TRUE))
}
#' @describeIn escape default escape coerces to character and escapes.
#' @export
escape.default <- function(x) {
escape.character(as.character(x))
}
#' @describeIn escape simply call escape on all elements of the list.
#' @export
escape.list <- function(x) {
lapply(x, escape)
}
escape_dots <- function(...) {
unlist(escape(eval(list(...))))
}
#' Character class escapes
#' @inheritParams escape
#' @export
character_class_escape <- function(x) UseMethod("character_class_escape")
#' @describeIn character_class_escape objects are passed through unchanged.
#' @export
character_class_escape.regex <- function(x) x
#' @describeIn character_class_escape objects are passed through unchanged.
#' @export
character_class_escape.character_class <- character_class_escape.regex
#' @describeIn character_class_escape objects properly escaped for character classes.
#' @export
character_class_escape.character <- function(x) {
chars <- c("-", "^", "[", "]", "\\")
regex(gsub(paste0("([\\", paste0(collapse = "\\", chars), "])"), "\\\\\\1", x, perl = TRUE))
}
#' @describeIn character_class_escape call \code{character_class_escape} on all elements of the list.
#' @export
character_class_escape.list <- function(x) {
lapply(x, character_class_escape)
}
#' @describeIn character_class_escape coerce to \code{character} and \code{character_class_escape}.
#' @export
character_class_escape.default <- function(x) {
character_class_escape.character(as.character(x))
}
character_class_escape_dots <- function(...) {
unlist(character_class_escape(eval(list(...))))
}