【发布时间】:2020-05-28 13:11:57
【问题描述】:
我想提取章节标题之间的所有文本,包括第一个/开始标题,但不包括结束标题。标题始终为大写字母,始终以数字-句点或数字-字母-句点组合开头,并始终后跟空格/s。我想保留副标题(即“6.1”、“7A.1”)作为提取字符串的一部分。这是一些示例文本:
example <- "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. 6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. 7A WARNING 7A.1 Do not forget to warn passengers."
# The output I want is:
"5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac."
"6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'."
"7A WARNING 7A.1 Do not forget to warn passengers."
使用stringr 包,并在post 的帮助下,我走到了这一步:
library(stringr)
str_extract_all(example, "(\\d+\\w?\\.?[:blank:]+[:upper:]+)(.*?)(?=\\d+\\w?\\.?[:blank:]+[:upper:]+)")
# Explanation of my regex code:
# (\\d+\\w?\\.?[[:blank:]]+[[:upper:]])
# \\d+ one or more digits
# \\w? zero or one letter
# \\.? zero or one period
# [:blank:]+ one or more space/tab
# [:upper]+ one or more capital letters
# (.*?) non-greedy capture, zero or one or more of any character
# (?=\\d+\\w?\\.?[:blank:]+[:upper:]+)
# ?= followed by
# \\d+ one or more digits
# \\w? zero or one letter
# \\.? zero or one period
# [:blank:]+ one or more space/tab
# [:upper]+ one or more capital letters
这非常接近我想要的,只有两件事出了问题。第一个是“6.1”它分裂成“6”。和“1”。第二个是最后一章标题之后的文本没有被捕获,看起来它可能会像“6.1”一样被拆分:
[[1]]
[1] "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. "
[2] "6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6."
[3] "1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. "
[4] "7A WARNING 7A."
我哪里错了??
【问题讨论】: