gpt4 book ai didi

正则表达式提取第三个数字

转载 作者:行者123 更新时间:2023-12-05 00:51:43 25 4
gpt4 key购买 nike

我有一些字符串,我正在尝试提取其中出现的第三个数字(在 R 中)。这是一个示例字符串,它们都具有相同的模式:

string = "Speaks 2 times (1%) for a total of 34 words (1%)."

我已经能够使用 str_extract(string, "[0-9]+") 获得第一个数字但我不知道如何只取第三个(字数)。任何帮助将不胜感激!

最佳答案

我们可以使用 str_locate 找到子串的位置并提取

library(stringr)
ind <- str_locate_all(string, "\\d+")[[1]][3,]
str_sub(string, ind[1], ind[2])
[1] "34"

或者使用 base Rstrsplit

setdiff(strsplit(string, "\\D+")[[1]], "")[3]
[1] "34"

数据

string <-  "Speaks 2 times (1%) for a total of 34 words (1%)."

关于正则表达式提取第三个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71394006/

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