gpt4 book ai didi

regex - R中一个字符串中的多个正则表达式

转载 作者:行者123 更新时间:2023-12-04 23:04:05 26 4
gpt4 key购买 nike

所以我有一个很长的字符串,我想处理多个匹配项。我似乎只能使用 regexpr 获得第一场比赛的第一个位置.如何在同一个字符串中获得多个位置(更多匹配)?

我正在寻找 html 源代码中的特定字符串。拍卖的标题(在 html 标签之间)。事实证明很难找到:

到目前为止,我使用这个:

locationstart <- gregexpr("<span class=\"location-name\">", URL)[[1]]+28
locationend <- regexpr("<", substring(URL, locationstart[1], locationend[1] + 100))
substring(URL, locationstart[1], locationstart[1] + locationend - 2)

也就是说,我寻找标题之前的部分,然后我捕捉那个地方,从那里寻找一个“<”,表示标题结束。我愿意提供更具体的建议。

最佳答案

使用 gregexpr允许多个匹配。

> x <- c("only one match", "match1 and match2", "none here")
> m <- gregexpr("match[0-9]*", x)
> m
[[1]]
[1] 10
attr(,"match.length")
[1] 5
attr(,"useBytes")
[1] TRUE

[[2]]
[1] 1 12
attr(,"match.length")
[1] 6 6
attr(,"useBytes")
[1] TRUE

[[3]]
[1] -1
attr(,"match.length")
[1] -1
attr(,"useBytes")
[1] TRUE

如果你想提取匹配,你可以使用 regmatches为你做那件事。
> regmatches(x, m)
[[1]]
[1] "match"

[[2]]
[1] "match1" "match2"

[[3]]
character(0)

关于regex - R中一个字符串中的多个正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16402083/

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