给定这个向量:
ba <- c('baa','aba','abba','abbba','aaba','aabba')'
我想将每个单词的最后一个 a
更改为 i
,除了 baa
和 aba
之外。
我写了以下行...
gsub('(?<=a[ab]b{1,2})a','i',ba,perl=T)
但被告知:PCRE 模式编译错误“lookbehind 断言不是固定长度”,位于“)a”。
我环顾四周,显然 R/Perl 只能向前查找可变宽度,而不能向后查找。有解决这个问题的方法吗?谢谢!
最佳答案
您可以使用后视替代方案 \K
来代替。此转义序列会重置报告的匹配的起点,并且不再包含任何先前消耗的字符。
引用 — rexegg
The key difference between \K and a lookbehind is that in PCRE, a lookbehind does not allow you to use quantifiers: the length of what you look for must be fixed. On the other hand, \K can be dropped anywhere in a pattern, so you are free to have any quantifiers you like before \K.
在上下文中使用它:
sub('a[ab]b{1,2}\\Ka', 'i', ba, perl=T)
# [1] "baa" "aba" "abbi" "abbbi" "aabi" "aabbi"
避免环视:
sub('(a[ab]b{1,2})a', '\\1i', ba)
# [1] "baa" "aba" "abbi" "abbbi" "aabi" "aabbi"
关于regex - R:可变宽度lookbehind的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308348/