R 只删除“[";“]"从字符串 [英] R remove only "[" "]" from string

查看:35
本文介绍了R 只删除“[";“]"从字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的东西:

test[1] 
"[0 30.5 4.5 10.5 2 35 22.999999999999996 29 5.500000000000001 23.5 18 23.5 44.5 3 44.5 44.00000000000001 43 27 42 35.5 19.5 44.00000000000001 1 0 31 34 18 1.5 26 6 45.99999999999999 10.5 9.5 24 20 42.5 14.5 45.5 20.499999999999996 150 45.5 0 4.5 22.5 4 9 8 0 0 15.5 30.5 7 5.500000000000001 12.5 33.5 15 500 22.5 18 43 4.5 26 23.5 16 4.5 7.5 32 0 0 18.5 33 31 14.5 21.5 0 40 0 0 43.49999999999999 22.999999999999996]"

我想删除每行的 [ 和 ](第一个和最后一个字符)(test[1] test[2] ...)但保留点数(22.9999).

And I would like to remove [ and ] (first and last characters) of each line (test[1] test[2] ...) but keep points (22.9999).

我尝试过一些 stringr 函数,但我不太喜欢正则表达式......你能帮我吗?

I have tried some stringr functions, but I'm not so go with regex ... Can you help me?

E

推荐答案

为此不需要包.只需使用以下内容:

There's no need for packages for this. Just use something like the following:

gsub("\\[|\\]", "", test)

这基本上是说:在 test 中查找 "[" 或 (|) "]", 如果你找到了,就用空替换它 ("")."

This basically says: "Look in test for "[" or (|) "]", and if you find it, replace it with nothing ("")."

由于 [] 是正则表达式中的特殊字符,因此需要对其进行转义.

Since [ and ] are special characters in regular expressions, they would need to be escaped.

如果您只是删除第一个和最后一个字符,您也可以执行以下操作:

If you're just removing the first and last character, you can also probably do something like:

substring(test, 2, nchar(test)-1)

这基本上是说,提取从第二个位置开始到倒数第二个位置结束的字符串部分."

This basically says, "Extract the part of the string starting from the second position and ending in the second-to-last position."

这篇关于R 只删除“[";“]"从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆