【发布时间】:2020-01-25 22:13:01
【问题描述】:
我想查找并替换string 的子字符串,但前提是该子字符串不在字符串的开头。我试过下面的代码,它给出了这些错误:
string <- c("some text followed by substring then more text followed by substring and then lots of text with lots of examples of substring and then more text", "substring at the beginning example with substring later in the string and then another substring blah blah, blah")
gsub("(?<!^)substring", "replacement", string)
Error in gsub("(?<!^)substring", "replacement", string) :
invalid regular expression '(?<!\^)substring', reason 'Invalid regexp'
gsub("(?<!\\^)substring", "replacement", string)
Error in gsub("(?<!\\^)substring", "replacement", string) :
invalid regular expression '(?<!\^)substring', reason 'Invalid regexp'
我正在使用以下代码,该代码有效但似乎不“正确”:
gsub("(.+?)substring", "replacement", string)
这是最好的选择吗?
【问题讨论】:
-
这里的
string是什么。前三种情况需要perl = TRUE -
啊,
perl = TRUE每次都杀了我!!我刚刚添加了string的示例 -
正如@Wiktor Stribiżew 所指出的,这个问题之前已经被明确提出并回答过(在搜索列表中的第 6 项中握拳),并且在多个 cmets 或答案stackoverflow.com/questions/26573611/… stackoverflow.com/questions/40251836/… stackoverflow.com/questions/58596135/…stackoverflow.com/questions/33930738/…
标签: r regex regex-lookarounds