| 1 |
# replace parts of a string with new values; `pos` is a matrix of positions and |
| 2 |
# each row is a pair of [start, end] |
| 3 |
str_replace = function(x, pos, value) { |
| 4 |
if (length(x) != 1) stop("Only a character scalar is supported.") |
| 5 |
# extract parts of the string that are outside [start, end] |
| 6 |
m = rbind(pos[, 1] - 1, pos[, 2] + 1) |
| 7 |
m = matrix(c(1, m, nchar(x)), nrow = 2) |
| 8 |
y = substring(x, m[1, ], m[2, ]) |
| 9 |
paste(rbind(y, c(value, '')), collapse = '') |
| 10 |
} |
| 11 |
|
| 12 |
# insert a value after i-th character in the string x |
| 13 |
str_insert = function(x, i, value) { |
| 14 |
if (i <= 0) return(paste0(value, x)) |
| 15 |
n = nchar(x) |
| 16 |
if (n == 0 || i >= n) return(paste0(x, value)) |
| 17 |
paste0(substr(x, 1, i), value, substr(x, i + 1, n)) |
| 18 |
} |
| 19 |
|
| 20 |
# a simplified replacement for stringr::str_locate_all() that returns a list |
| 21 |
# having an element for every element of 'string'; every list element is an |
| 22 |
# integer matrix having a row per match, and two columns: 'start' and 'end'. |
| 23 |
str_locate = function(x, pattern, all = TRUE) { |
| 24 |
out = (if (all) gregexpr else regexpr)(pattern, x, perl = TRUE) |
| 25 |
if (all) lapply(out, location) else location(out) |
| 26 |
} |
| 27 |
|
| 28 |
location = function(x) { |
| 29 |
len = attr(x, 'match.length') |
| 30 |
if (length(x) == 1 && x == -1) x = integer() |
| 31 |
cbind(start = x, end = x + len - 1L) |
| 32 |
} |
| 33 |
|
| 34 |
# a replacement for stringr::str_extract_all() |
| 35 |
str_extract = function(x, pattern) { |
| 36 |
m = gregexpr(pattern, x, perl = TRUE) |
| 37 |
regmatches(x, m) |
| 38 |
} |
| 39 |
|
| 40 |
str_match = function(x, pattern) { |
| 41 |
# gregexec() was added in R 4.1.0; for lower versions of R, use fallback |
| 42 |
if (is.function(gregexec <- baseenv()[['gregexec']])) { |
| 43 |
m = gregexec(pattern, x, perl = TRUE) |
| 44 |
} else { |
| 45 |
x = unlist(str_extract(x, pattern)) |
| 46 |
m = regexec(pattern, x, perl = TRUE) |
| 47 |
} |
| 48 |
do.call(cbind, regmatches(x, m)) |
| 49 |
} |