regex - R:可变宽度lookbehind的解决方法

标签 regex r lookbehind

给定这个向量:

ba <- c('baa','aba','abba','abbba','aaba','aabba')'

我想将每个单词的最后一个 a 更改为 i,除了 baaaba 之外。

我写了以下行...

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/

相关文章:

r - Bass模型遗传算法的R实现

r - data.table 通过表达式快速访问列

java - 回顾中的反向引用

java - 正则表达式高级 : Positive lookbehind

python - 将 re.search 函数应用于 Python 中的列

ruby - 用于查找最多 n 个连续模式的正则表达式

R:如何修改ggplotly中的图例?

regex - Google Analytics 漏斗步骤的正则表达式

php - 正则表达式:SQL 查询字符串匹配 * 或 .* 但计数 (*)

c# - 使用 .NET 正则表达式解析引号之间的文本