我有这样的字符串:
a = "USER 2020-02-09 01:13SOMETHING INTERESTING HERE.USER 2020-02-10 08:30and something else comes here"
我想提取HH:MM时间和关键字“ USER”之间的所有内容。
如果我使用正则表达式使用来定位时间说明和USER之间的时间,则会sringr::str_extract_all
得到:
str_extract_all(a, pattern = '([0-9]{2,}:[0-9]{2,})(.*)(?=USER)')
# [[1]]
# [1] "01:13SOMETHING INTERESTING HERE."
我可以在正则表达式中添加什么,使其在HH:MM和USER之间或在HH:MM和字符串的末尾之间进行搜索(这样我也会得到08:30and something else comes here
)?
我们可以使用正则表达式环顾四周
library(stringr)
str_extract(a, "(?<=\\b\\d{2}:\\d{2}).*(?=USER)")
#[1] "SOMETHING INTERESTING HERE."
如果我们要提取所有成分
str_extract_all(a, "(?<=\\b\\d{2}:\\d{2}).*(?=USER)|(?<=\\b\\d{2}:\\d{2})[^0-9]+$")
#[[1]]
#[1] "SOMETHING INTERESTING HERE." "and something else comes here"
或者以更紧凑的方式
str_extract_all(a, "(?<=\\b\\d{2}:\\d{2})[^0-9]+(?=(USER)|$)")
#[[1]]
#[1] "SOMETHING INTERESTING HERE." "and something else comes here"
如果还需要时间部分
str_extract_all(a, "\\b\\d{2}:\\d{2}[^0-9]+(?=(USER)|$)")
#[[1]]
#[1] "01:13SOMETHING INTERESTING HERE." "08:30and something else comes here"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句