从字符串中删除两个字符

时间:2022-02-28 17:07:46

Related question here.

相关问题在这里。

So I have a character vector with currency values that contain both dollar signs and commas. However, I want to try and remove both the commas and dollar signs in the same step.

所以我有一个货币值包含美元符号和逗号的字符向量。但是,我想尝试在同一步骤中删除逗号和美元符号。

This removes dollar signs =

这会删除美元符号=

d = c("$0.00", "$10,598.90", "$13,082.47")
gsub('\\$', '', d)

This removes commas =

这会删除逗号=

library(stringr)
str_replace_all(c("10,0","tat,y"), fixed(c(","), "")

I'm wondering if I could remove both characters in one step.

我想知道我是否可以一步删除这两个字符。

I realize that I could just save the gsub results into a new variable, and then reapply that (or another function) on that variable. But I guess I'm wondering about a single step to do both.

我意识到我可以将gsub结果保存到一个新变量中,然后在该变量上重新应用该(或另一个函数)。但我想我想知道一步到位。

2 个解决方案

#1


12  

Since answering in the comments is bad:

由于评论中的回答很糟糕:

gsub('\\$|,', '', d)

replaces either $ or (|) , with an empty string.

用空字符串替换$或(|)。

#2


3  

take a look at ?regexp for additional special regex notation:

看一下?regexp以获得额外的特殊正则表达式:

> gsub('[[:punct:]]', '', d)
[1] "000"     "1059890" "1308247"

#1


12  

Since answering in the comments is bad:

由于评论中的回答很糟糕:

gsub('\\$|,', '', d)

replaces either $ or (|) , with an empty string.

用空字符串替换$或(|)。

#2


3  

take a look at ?regexp for additional special regex notation:

看一下?regexp以获得额外的特殊正则表达式:

> gsub('[[:punct:]]', '', d)
[1] "000"     "1059890" "1308247"