cd ..

:~/Is it Math? with Regex (9/20/2022)


Occasionally, I write R shiny apps that allow users to input mathematical expressions. R then parses these expressions as R code. The problem with this is that without "sanitizing" the input, users can make my Shiny server execute all kinds of code I don't want. Here is a solution to parsing the input with regex to check that it only uses "allowed" functions.
check_math <- function(string){
  allowed_functions <- c("log","sin","min","max","")
  matches <- regmatches(string,gregexec("\\W(\\w)\\(.?\\)",string))
  matches <- matches[[1]][2,] 
  ok <- all(matches %in% allowed_functions)
  return(ok)
}
This code looks for all instances of some letters followed by a set of parentheses. It checks those matches against a list of allowed functions and returns TRUE only if all of them are in the allowed set. All uses of parentheses that are not preceeded by letters are allowed by including the empty string in the allowed functions.
check_math("x1^(2)*x2^(3) %>% rep(1,1000000)")
[1] FALSE 
check_math("x1^(2)*x2^(3)")
[1] TRUE