R:使用gsub捕获无匹配的反向引用

时间:2017-08-03 18:05:41

标签: r regex

我正在尝试使用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)

1 个答案:

答案 0 :(得分:2)

您可以匹配并捕获不包含括号的字符串,然后用f()包裹它;对于在其中有括号的字符串,由于它们不匹配模式,它们将保持不变:

sub("^([^()]+)$", "f(\\1)", a)
# [1] "x(1)"   "y(212)" "z(b)"   "f(234)" "f(cd)"