【问题标题】:Removing characters after a EURO symbol in R在R中删除欧元符号后的字符
【发布时间】:2015-07-08 09:22:57
【问题描述】:

我有一个欧元符号保存在“欧元”变量中:

euro <- "\u20AC"
euro
#[1] "€"

并且“eurosearch”变量包含“本 SOW 中定义的服务,价格为 15,896.80 欧元(如果执行)。

eurosearch
[1] "services as defined in this SOW at a price of € 15,896.80 (if executed fro"

我想要欧元符号后面的字符“15,896.80(如果执行的话” 我正在使用此代码:

gsub("^.*[euro]","",eurosearch)

但我得到的结果是空的。如何获得预期的输出?

【问题讨论】:

  • 您希望15,896.80 (if executed fro 作为结果输出吗?还是15,896.80
  • 我需要“€ 15,896.80”,但是使用一个变量,这个例子是 € ,下次它可以是 $ ,它将保存在 'euro' 变量中

标签: regex r gsub stringr


【解决方案1】:

stringr 等中使用base r 或str_extarct 中存在的正则匹配

> x <- "services as defined in this SOW at a price of € 15,896.80 (if executed fro"
> regmatches(x, regexpr("(?<=€ )\\S+", x, perl=T))
[1] "15,896.80"

> gsub("€ (\\S+)|.", "\\1", x)
[1] "15,896.80"

使用变量。

euro <- "\u20AC"
gsub(paste(euro , "(\\S+)|."), "\\1", x) 

如果这个使用变量的答案对你不起作用,那么你需要设置编码,

gsub(paste(euro , "(\\S+)|."), "\\1", `Encoding<-`(x, "UTF8"))

Source

【讨论】:

  • 我可以在第二个答案中使用变量代替€,而不是直接输入€,我希望它是可变的,假设这次€保存在某个变量中,下次它可以是$,所以!?
  • 试试gsub(paste(euro , "(\\S+)|."), "\\1", x)
  • $ 的问题在于它是一个元字符,因此需要进行一些修改。
  • No @Avinash Raj ,值为空。
  • x &lt;- "services as defined in this SOW at a price of € 15,896.80 (if executed fro" ; euro &lt;- "€" ; gsub(paste(euro , "(\\S+)|."), "\\1", x) 非常适合我。
【解决方案2】:

您可以通过使用paste0 连接字符串来在模式中使用变量:

euro <- "€"
eurosearch <- "services as defined in this SOW at a price of € 15,896.80 (if executed fro"
sub(paste0("^.*", gsub("([^A-Za-z_0-9])", "\\\\\\1", euro), "\\s*(\\S+).*"), "\\1", eurosearch)

euro <- "$"
eurosearch <- "services as defined in this SOW at a price of $ 25,196.4 (if executed fro"
sub(paste0("^.*", gsub("([^A-Za-z_0-9])", "\\\\\\1", euro), "\\s*(\\S+).*"), "\\1", eurosearch)

CodingGround demo

请注意,使用gsub("([^A-Za-z_0-9])", "\\\\\\1", euro),我将转义任何非单词符号,以便$ 可以被视为文字,而不是特殊的正则表达式元字符(取自this SO post)。

【讨论】:

    猜你喜欢
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2021-02-20
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多