我已经抓取了 HTML,现在我有这样的行:
rows
1: for the Year Ended 31 March 2013
我只想提取表达式 "31 March 2013"
。表达式周围的文本可能会有所不同。表达式要转成日期格式,最好是31-3-2013
如何解决这个问题?
最佳答案
如果您的字符串中没有其他数字,您可以使用以下方法:
string <- "for the Year Ended 31 March 2013"
format(as.Date(sub(".*?(\\d+ \\w+ \\d+).*", "\\1", string),
"%d %B %Y"), "%d-%m-%Y")
# [1] "31-03-2013"
这里sub
提取相关的子字符串,as.Date
创建一个表示Date
值的对象,format
更改日期元素的顺序。
它也适用于额外的文本和一位数的日期:
string <- c("for the Year Ended 31 March 2013",
"1 January 2013 the Year Began",
"for the Year Ended 31 March 2013 and not now")
format(as.Date(sub(".*?(\\d+ \\w+ \\d+).*", "\\1", string),
"%d %b %Y"), "%d-%m-%Y")
# [1] "31-03-2013" "01-01-2013" "31-03-2013"
关于regex - 在 R 中重新格式化抓取的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21381153/