[英]Multiple regexpr in one string in R
所以我有一个很长的字符串,我想处理多个匹配项。 我似乎只能使用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)
gregexpr
的回答中建议的gregexpr
和regmatches
允许在字符串中提取正则表达式模式的多个实例。 此外,该解决方案的优势在于完全依赖 R 的{base}
包,而不需要额外的包。
无论如何,我想建议一个基于stringr 包的替代解决方案。 通常,该包通过提供基本 R 的各种字符串支持函数的大部分功能(不仅仅是与正则表达式相关的函数),以及一组直观命名并提供一致的函数,使处理字符串变得更容易应用程序接口。 实际上,stringr 函数不仅取代了基本的 R 函数,而且在许多情况下还引入了附加功能; 例如,stringr 的正则表达式相关函数针对字符串和模式都进行了矢量化。
具体针对长字符串中提取多个模式的问题,可以使用str_extract_all
和str_match_all
,如下图所示。 根据输入是单个字符串或它的向量这一事实,可以使用列表/矩阵下标、 unlist
列表或其他方法(如lapply
、 sapply
等)来调整逻辑。重点是 stringr 函数返回的结构可以用于访问我们想要的东西。
# simulate html input. (Using bogus html tags to mark the target texts; the demo works
# the same for actual html patterns, the regular expression is just a bit more complex.
htmlInput <- paste("Lorem ipsum dolor<blah>MATCH_ONE<blah> sit amet, purus",
"sollicitudin<blah>MATCH2<blah>mauris, <blah>MATCH Nr 3<blah>vitae donec",
"risus ipsum, aenean quis, sapien",
"in lorem, condimentum ornare viverra",
"suscipit <blah>LAST MATCH<blah> ipsum eget ac. Non senectus",
"dolor mauris tellus, dui leo purus varius")
# str_extract() may need a bit of extra work to remove the leading and trailing parts
str_extract_all(htmlInput, "(<blah>)([^<]+)<")
# [[1]]
# [1] "<blah>MATCH_ONE<" "<blah>MATCH2<" "<blah>MATCH Nr 3<" "<blah>LAST MATCH<"
str_match_all(htmlInput, "<blah>([^<]+)<")[[1]][, 2]
# [1] "MATCH_ONE" "MATCH2" "MATCH Nr 3" "LAST MATCH"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.