简体   繁体   English

正则表达式模式后面跟着字母“k”

[英]regex pattern a few numbers followed by the letter “k”

I would like to replace k in a string with 000. For instance, I want to make "£50000" from "£50k". 我想用000替换字符串中的k。例如,我想从“£50k”中赚取“£50000”。 Note that the function can be applied to cases like "£50k king", which should result in "£50000 king". 请注意,该功能可以应用于“£50k king”这样的情况,这将导致“£50000 king”。

Here's what I have so far: 这是我到目前为止所拥有的:

replace_k = function(data){
data = gsub("^[0-9]k", "[0-9]000", data)
return(data)
} 

怎么样

data = gsub("([0-9]+)k", "\\1000", data)

You may use the following solution to handle K , M and G (and more if you want, just adjust the ToDigits function): 您可以使用以下解决方案来处理KMG (如果需要,可以使用更多,只需调整ToDigits函数):

> library(gsubfn)
> x <- "0.56K 50K 1.5M 56.56G"
> ToDigits <- function(s) {ifelse(s=="K", 1000, ifelse(s=="M", 1000000, 1000000000)) }
> gsubfn("(\\d*\\.?\\d+)([KMG])", function(y,z) as.numeric(y) * ToDigits(z), x)
[1] "560 50000 1500000 5.656e+10"

Here, (\\\\d*\\\\.?\\\\d+)([KMG]) captures 0+ digits, . 在这里, (\\\\d*\\\\.?\\\\d+)([KMG])捕获0+位数, . and 1+ digits into Group 1 and then K or M or G into Group 2, and gsubfn is used to manipulate the found match in such a way that the found number is multipled with the right value obtained using a simple helper ToDigits function (if K is in Group 2, multiply with 1000 , etc.) 并且1+数字进入第1组,然后KMG进入第2组, gsubfn用于操纵找到的匹配,使得找到的数字与使用简单助手ToDigits函数获得的正确值ToDigits (如果K在第2组中,乘以1000 ,等等。)

To make it case insensitive, you may tweak the code above as 为了使它不区分大小写,您可以将上面的代码调整为

> ToDigits <- function(s) {ifelse(tolower(s)=="k", 1000, ifelse(tolower(s)=="m", 1000000, 1000000000)) }
> gsubfn("(\\d*\\.?\\d+)([KMGkmg])", function(y,z) as.numeric(y) * ToDigits(z), x)
[1] "560 50000 1500000 5.656e+10"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM