Here's one way, first, you define your variable names and then give a regular expression that would match your operators, then we can make a validater function
par.names<- c("P1", "P2", "P3")
operators <- "[*+]"
get_checker <- function(par.names, operatorsRE) {
function(x) {
nonops <- strsplit(x, operatorsRE)
sapply(nonops, function(x) all(x %in% par.names))
}
}
checker <- get_checker(par.names, operators)
We just use an enclosure to keep everything in a tidy function. Then we can use that to validate input
input <- c("P1+P2*P3", "P1+P5*P$4")
checker(input)
# [1] TRUE FALSE
Here's a version that will allow you to pass an array of operators instead.
par.names<- c("P1", "P2", "P3")
operators <- c("^", "*","+")
get_checker <- function(par.names, operators) {
operatorsRE <- paste0("(", paste(Hmisc::escapeRegex(operators), collapse="|"),")")
function(x) {
nonops <- strsplit(x, operatorsRE)
sapply(nonops, function(x) all(x %in% par.names))
}
}
That way you can avoid regular expression quirks but this does use the Hmisc package for a helper function.