gpt4 book ai didi

R 正则表达式 : retrieve currency abbreviations

转载 作者:行者123 更新时间:2023-12-04 10:30:39 26 4
gpt4 key购买 nike

我有一串变量名,我想从中提取一个向量给出的货币。但是我在提取值时遇到困难。

我的第一个方法是将除货币缩写外的所有缩写替换为空。

例如:

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"

预期结果将是 c("USD", "EUR", "")

这显然是错误的,因为它匹配单个字符(E、U、R)而不是字符组(EUR)。现在我的问题是,我怎样才能只提取给定的组?

最佳答案

你可以使用

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))

参见 R demo online

输出:

[[1]]
[1] "USD"

[[2]]
[1] "EUR"

[[3]]
character(0)

如果货币看起来“粘”在数字上,您需要删除单词边界 (\b)。

关于R 正则表达式 : retrieve currency abbreviations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41126000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com