Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R regex:检索货币缩写_R_Regex - Fatal编程技术网

R regex:检索货币缩写

R regex:检索货币缩写,r,regex,R,Regex,我有一个变量名字符串,我想从中提取向量给定的货币。但我很难提取这些值 我的第一个方法是将除了货币缩写以外的所有货币都替换为零 例如: x <- c("Total Assets in th USD", "Equity in mil EUR", "Number of Branches") currencies <- c("USD", "EUR", "GBP") regex <- paste0("([^", paste(currencies, col

我有一个变量名字符串,我想从中提取向量给定的货币。但我很难提取这些值

我的第一个方法是将除了货币缩写以外的所有货币都替换为零

例如:

x <- c("Total Assets in th USD", "Equity in mil EUR", "Number of Branches")
currencies <- c("USD", "EUR", "GBP")

regex <- paste0("([^",
                paste(currencies, collapse = "|"),
                "])")
# results in
# "([^USD|EUR|GBP])"

gsub(regex, "", x)
# [1] "USD"  "EEUR" "B" 

x我们可以使用
stru-extract

library(stringr)
str_extract(x, paste(currencies, collapse="|"))
#[1] "USD" "EUR" NA   

或者使用
sub
from
base R

v1 <- sub(paste0(".*\\b(", paste(currencies, collapse="|"), ")\\b.*"), "\\1", x)
replace(v1, !v1 %in% currencies, "")
#[1] "USD" "EUR" ""   
v1您可以使用

x <- c("Total Assets in th USD", "Equity in mil EUR", "Number of Branches")
currencies <- c("USD", "EUR", "GBP")

regex <- paste0("\\b(",
                    paste(currencies, collapse = "|"),
                ")\\b")
# results in
# "\b(USD|EUR|GBP)\b"

regmatches(x, gregexpr(regex, x))

如果货币与数字“粘在一起”,你需要删除单词边界(
\b
)。

我们可以只使用基本正则表达式吗?@David发布了一个基本R选项你可以通过
sapply(货币,函数(y){grep(pattern=y,x,value=F)}
如果我搜索
[R],得到一个简单的匹配列表regex currency
我只找到一篇相关的文章,但没有解决我的问题()。能不能请你帮我把硼酸盐擦掉?该死的。我把你的帖子和另一篇混在一起了。如果你只是做任何形式的编辑(例如删除不必要的“谢谢”,这是不赞成的),那么我的否决票可以被推翻。不用担心,这就是我为什么问的原因!:)此外,如果需要取消列出结果并获取空字符串,您可能需要查看。stringr函数可以完成这项工作。
[[1]]
[1] "USD"

[[2]]
[1] "EUR"

[[3]]
character(0)