如果字符串包含在模式中,如何替换它的一部分

How can I replace part of a string if it is included in a pattern

我正在寻找一种方法来替换以下每个字符中的所有 _(比如 ''

x <- c('test_(match)','test_xMatchToo','test_a','test_b') 

当且仅当 _ 后跟 (x。所以想要的输出是:

x <- c('test(match)','testxMatchToo','test_a','test_b') 

如何做到这一点(使用任何包都可以)?

使用 lookahead:

_(?=[(x])

前瞻所做的是断言模式匹配,但实际上并不匹配它正在寻找的模式。因此,在这里,最终匹配文本仅包含下划线,但前瞻断言其后跟 x(.

Demo on Regex101

您的 R 代码看起来有点像这样(为清楚起见,每行一个参数):

gsub(
    "_(?=[(x])",                            # The regex
    "",                                     # Replacement text
    c("your_string", "your_(other)_string"), # Vector of strings
    perl=TRUE                               # Make sure to use PCRE
)