简体   繁体   中英

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". Note that the function can be applied to cases like "£50k king", which should result in "£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):

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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