Skip to content

Commit 2fb7e0f

Browse files
committed
Escaped regex characters in variable_dims()
1 parent 1d58078 commit 2fb7e0f

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

R/csv.R

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -983,7 +983,9 @@ variable_dims <- function(variable_names = NULL) {
983983
uniq_variable_names <- unique(gsub("\\[.*\\]", "", variable_names))
984984
var_names <- gsub("\\]", "", variable_names)
985985
for (var in uniq_variable_names) {
986-
pattern <- paste0("^", var, "\\[")
986+
# escape regex symbols
987+
esc_var <- gsub("([][{}()+*?.^$|\\\\])", "\\\\\\1", var)
988+
pattern <- paste0("^", esc_var, "\\[")
987989
var_indices <- var_names[grep(pattern, var_names)]
988990
var_indices <- gsub(pattern, "", var_indices)
989991
if (length(var_indices)) {

tests/testthat/test-csv.R

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,19 @@ test_that("read_cmdstan_csv() fails with the no params listed", {
9595
"Supplied CSV file does not contain any variable names or data!")
9696
})
9797

98+
test_that("variable_dims works for standard Stan names", {
99+
vars <- c("beta[1]", "beta[2]", "beta[3]", "sigma")
100+
dims <- variable_dims(vars)
101+
expect_equal(dims$beta, 3)
102+
expect_equal(dims$sigma, 1)
103+
})
104+
105+
test_that("variable_dims handles names with regex metacharacters", {
106+
vars <- c('SIGMA(1,1)[1,2]', 'SIGMA(1,1)[2,2]')
107+
dims <- variable_dims(vars)
108+
expect_equal(dims[["SIGMA(1,1)"]], c(2, 2))
109+
})
110+
98111
test_that("read_cmdstan_csv() matches utils::read.csv", {
99112
csv_files <- c(test_path("resources", "csv", "model1-1-warmup.csv"),
100113
test_path("resources", "csv", "model1-2-warmup.csv"))

0 commit comments

Comments
 (0)