stringr:从字符串中删除圆括号和方括号 [英] stringr: Removing Parentheses and Brackets from string
本文介绍了stringr:从字符串中删除圆括号和方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中删除圆括号和方括号.我得到了所需的结果,但正在寻找更紧凑的方法.
I want to remove parentheses and brackets from a string. I got the required result, however looking for more compact method.
Test <- c("-0.158)", "0.426)", "1.01)", "1.6)", "2.18)", "2.77]")
stringr::str_replace(
string = Test
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77]"
stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
# [1] "-0.158)" "0.426)" "1.01)" "1.6)" "2.18)" "2.77"
stringr::str_replace(
string = stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
想知道是否可以通过这样的单个命令获得它
Wonder if it can be obtained with a single command something like this
stringr::str_replace(
string = Test
, pattern = "\\)^]"
, replacement = ""
)
已编辑
找到了一个非常简单的解决方案
Found a very simple solution
readr::parse_number(Test)
[1] -0.158 0.426 1.010 1.600 2.180 2.770.
推荐答案
我们可以使用|
gsub("\\)|\\]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
或者不是转义,而是将括号放在 []
or instead of escaping place the brackets inside the []
gsub("[][()]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
<小时>
如果我们想要进行提取而不是删除,请使用 base R
中的 gregexpr/regmatches
或 stringr<中的
str_extract
/code> 检查数字可以以 -
开头并包含 的模式.
If we want to do the extract instead of removing use either gregexpr/regmatches
from base R
or str_extract
from stringr
to check for patterns where a number could start with -
and include .
library(stringr)
str_extract(Test, "-?[0-9.]+")
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
这篇关于stringr:从字符串中删除圆括号和方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文