r - 查找不在字符串开头的子字符串
问题描述
我想查找并替换 a 的子字符串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)
这是最好的选择吗?
解决方案
问题是perl = TRUE
默认情况下FALSE
根据?gsub
gsub(模式,替换,x,ignore.case = FALSE,perl = FALSE,fixed = FALSE,useBytes = FALSE)
gsub("(?<!^)substring", "replacement", string, perl = TRUE)
#[1] "some text followed by replacement then more text followed by replacement and then lots of text with lots of examples of replacement and then more text"
#[2] "substring at the beginning example with replacement later in the string and then another replacement blah blah, blah"
推荐阅读
- c++ - 函数中的“key”是否具有相同的含义?
- javascript - 使用JS检查输入字段中的数值
- html - 如何将下拉框(在表单中)的选定选项的值从 html 传递到 ts 文件,而不在 Angular 中提交表单
- sql - 尝试从 SQL 中的当前日期获取上个月的第一个月和最后一个月时出错
- python - 代码第二次循环时bs4出错
- firebase - 如何找到适用于 firebase 实时数据库和颤振的文档?
- json - 烧瓶返回json序列
- c++ - 指向字符串数组中字符的指针的 C++ 指针
- docker - 由于 RAM 中断,Docker Compose WSL2 就像一盏圣诞灯
- python - 将“类似地图”的可调用对象传递给 scipy 的差分进化