问题
I have a something like :
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]"
And I would like to remove [ and ] (first and last characters) of each line (test[1] test[2] ...) but keep points (22.9999).
I have tried some stringr functions, but I'm not so go with regex ... Can you help me?
E
回答1:
There's no need for packages for this. Just use something like the following:
gsub("\\[|\\]", "", 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."
回答2:
One easy way to remove [
and ]
from a string is
x <- "[12345]"
gsub("[][]", "", x)
# [1] "12345"
Here, the outer []
means one of the characters in the brackets. The inner ][
represent the to-be-replaced characters.
来源:https://stackoverflow.com/questions/24993337/r-remove-only-from-string