簡體   English   中英

R 中的正則表達式:查找數字后跟模式

[英]Regex in R : Find number followed by a pattern

我正在嘗試制作一個正則表達式,它可以在模式匹配后提取來自任何地方的數字。

df <-as.data.frame(cbind(c("The 100 price of apple is 2/1 and could be more than 30 ",
                           "The 200 price of fruits can be 20-1  and I am not sure how much it can decrease it can be 1", 
                           "The price is 120", 
                           "The price can be anything but less than 30 1", 
                           "The price 10",'there is price')))
df$v2 <- str_extract(df$V1, "price[^a-zA-Z]+\\d+.*")

我在 v2 中預期的 output,基本上是價格后的第一個數字,可以是 /- 或空格后跟數字(2/1 或 2-1 或 2 1:價格 2/1
價格 20-1
價格 120
價格 30 1
價格 10
未找到
問候, R

您可以使用sub提取"price"之后的數字。

sub('.*price.*?(\\d+)', '\\1', df$V1)
#[1] "2/1"  "20-1" "120"  "30 1" "10"  

對於更新的數據,我們可以使用:

stringr::str_match(df$V1, '.*price.*?(\\d+[-/ ]?\\d+?).*')[, 2]
#[1] "2/1"  "20-1" "120"  "30 1" "10"   NA   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM