我正在尝试使用regex
执行某些操作并返回引用,这些引用涉及抓取其中没有函数的字符串并将它们放在f(x)
函数中。
a <- c("x(1)","y(212)", "z(b)","234", "cd")
gsub("solution", "f\\(\\1\\)", a)
# "x(1)" "y(212)" "z(b)" "f(234)" "f(cd)"
# Naively I have tried the following:
gsub("(.*)&[^(*.\\(.*\\))]", "f\\(\\1\\)", a)
gsub("(.*)&[!(*.\\(.*\\))]", "f\\(\\1\\)", a)
gsub("(.*)&(!(*.\\(.*\\)))", "f\\(\\1\\)", a)
答案 0 :(得分:2)
您可以匹配并捕获不包含括号的字符串,然后用f()
包裹它;对于在其中有括号的字符串,由于它们不匹配模式,它们将保持不变:
sub("^([^()]+)$", "f(\\1)", a)
# [1] "x(1)" "y(212)" "z(b)" "f(234)" "f(cd)"