在R字符串中的特定位置插入char

时间:2021-01-13 20:03:50

I have a R string like this

我有一个像这样的R字符串

a <- "(hi I am (learning R) )" 

I want to add a character "x" in above string and make it like

我想在上面的字符串中添加一个字符“x”并使它像

"(hi I am (learning R)x )" 

How can I do that using R efficiently?

我怎样才能有效地使用R?

Edit : Adding 1 more information: Assume that the pattern can change for starting character string but last 2 bracket in the end will remain same all the time and I have to insert x between them all the time.

编辑:添加1个更多信息:假设模式可以更改为起始字符串但最后2个括号将始终保持相同,我必须始终在它们之间插入x。

1 个解决方案

#1


2  

You can use sub, capture the unique pattern that you want to insert after and then use back reference to add x:

您可以使用sub,捕获您想要插入的唯一模式,然后使用back引用添加x:

sub("(R\\))", "\\1x", a)
# [1] "(hi I am (learning R)x )"

Update on inserting character between two brackets at the end of the string, the simplest would be match a pattern and replace it with your desired one:

更新在字符串末尾的两个括号之间插入字符,最简单的方法是匹配一个模式并将其替换为您想要的一个:

sub("\\) \\)$", "\\)x \\)", a)
# [1] "(hi I am (learning R)x )"

#1


2  

You can use sub, capture the unique pattern that you want to insert after and then use back reference to add x:

您可以使用sub,捕获您想要插入的唯一模式,然后使用back引用添加x:

sub("(R\\))", "\\1x", a)
# [1] "(hi I am (learning R)x )"

Update on inserting character between two brackets at the end of the string, the simplest would be match a pattern and replace it with your desired one:

更新在字符串末尾的两个括号之间插入字符,最简单的方法是匹配一个模式并将其替换为您想要的一个:

sub("\\) \\)$", "\\)x \\)", a)
# [1] "(hi I am (learning R)x )"