Я хочу извлечь весь текст между заголовками глав, включая первый / начальный заголовок, но исключая закрывающий заголовок. Заголовки всегда пишутся в верхнем регистре, им всегда предшествует комбинация di git -period или di git -letter-period, и всегда следует пробел / 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
и с помощью этого сообщения , я дошел до этого:
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."
Где я ошибаюсь ??