r - 如何根据R中分隔符之间的出现替换字符串中的确切字符数

标签 r regex backreference

我有这样的文本字符串:

u <- "she goes ~Wha::?~ and he's like ~↑Yeah believe me!~ and she's etc."
我想要做的是替换成对之间出现的所有字符 ~分隔符(包括分隔符本身),例如 X .
gsub方法替换 ~ 之间的子串-分隔符与单个 ​​X 配对:
gsub("~[^~]+~", "X", u)
[1] "she goes X and he's like X and she's etc."
但是,我真正想做的是用 X 替换分隔符(和分隔符本身)之间的每个字符。 .所需的输出是这样的:
"she goes XXXXXXXXX and he's like XXXXXXXXXXXXXXXXXXX and she's etc."
我一直在试验 nchar 、反向引用和 paste如下,但结果不正确:
gsub("(~[^~]+~)", paste0("X{", nchar("\\1"),"}"), u)
[1] "she goes X{2} and he's like X{2} and she's etc."
任何帮助表示赞赏。

最佳答案

paste0("X{", nchar("\\1"),"}")代码结果 X{2}因为 "\\1"是长度为 2 的字符串。\1如果您不在字符串模式中使用它,则不会将其插入为反向引用。
您可以使用以下基于 stringr 的解决方案:

> u <- "she goes ~Wha::?~ and he's like ~↑Yeah believe me!~ and she's etc."
> str_replace_all(u, '~[^~]+~', function(x) str_dup("X", nchar(x)))
[1] "she goes XXXXXXXX and he's like XXXXXXXXXXXXXXXXXXX and she's etc."
找到与 ~[^~]+~ 的匹配项后,该值被传递给匿名函数和 str_dupX 创建一个字符串与匹配值的长度相同。

关于r - 如何根据R中分隔符之间的出现替换字符串中的确切字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64352074/

相关文章:

r - gstat变异函数中的距离单位是多少?

python - python中该公式的具体正则表达式

regex - 在 postgresql 中使用函数修改反向引用

r - 翻转 gg TreeMap

r - 使用 data.table : column missing from the output 的非 equi 连接

javascript - 正则表达式查找大括号内的字符串Javascript

python - 使用正则表达式从字符串中提取子字符串

正则表达式 - 反向引用 - 单词定界符?

regex - 在 PostgreSQL 中匹配部分反向引用

重新排列和排序