【问题标题】:Extract Date from HTML page using regex in R language使用 R 语言中的正则表达式从 HTML 页面中提取日期
【发布时间】:2018-06-12 05:53:54
【问题描述】:

如何使用 REGEX 仅提取 title="11:53 AM - 27 May 2018" 中的日期。

仅供参考,这是来自 HTML 页面。我想使用 R 语言将所有这些匹配项提取到一个列表中。

我的输出应该是 2018 年 5 月 27 日。

提前感谢您的宝贵时间:)

【问题讨论】:

  • 我认为您应该使用 DOM 解析器来提取 title 属性。在此之后,您还可以使用正则表达式。

标签: html r regex


【解决方案1】:

考虑到您有要在其中查找日期的页面的 HTML 代码,最简单的方法是使用正则表达式查找代码的所有部分 title="11:53 AM - 27 May 2018" 然后你可以简单地再次使用正则表达式从字符串中提取日期。 我已经写了一个基本的代码,你可以根据你的需要修改它并使用它。

first_match <- regexpr(pattern='title\\s*=\\s*"\\d\\d:\\d\\d\\s*(AM|PM)\\s*-\\s*\\d\\d\\s[a-zA-Z]{3}\\s\\d{4}"', str)`
match_str <- regmatches(str,m)
date_exp <- regexpr(pattern='\\d\\d\\s[a-zA-Z]{3}\\s\\d{4}', match_str)
date <- regmatches(match_str, date_exp)

date 是您需要的输出,str 是字符串形式的代码。

【讨论】:

  • sub(".*-","",your_string) 就是你要找的东西
【解决方案2】:

想通了:

rawHTML <- paste(readLines("D:\\practicum\\CSK.html"), collapse="\n")

b<-unlist(str_match_all(rawHTML, '\\d{2} \\w+ 2018'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多