首页 > 解决方案 > 如何提取特定字符串后跟任意数字?

问题描述

我有一个小问题。我有这种格式的文本:

A.1 Goals

Section 1: Blah Blah Blah
Random sentence A. Random sentence.
Section 2: Blah Blah Blah
Random sentence A.
Random sentence.

A.2 description

我想获得以下输出:

A.1 Goals

Section 1: Blah Blah Blah

Section 2: Blah Blah Blah

A.2 description

所以基本上如何获得任何重复多次并后跟任何可能数字的字符串(相同字符串和不同数字的任何模式)

标签: r

解决方案


我们可以grep在阅读后使用readLines. 在这里,我们匹配字母(“A”后跟 a.后跟一个或多个数字 - \\d+)或 ( |) 如果文本以“Section”开头 ( ^Section) 后跟一些字符 ( .*) 并且如果有重复的单词后跟空格((\\w+\\s*)\\1-\\1是捕获组的反向引用)

out <- grep("(^A\\.\\d+)|(^Section.*\\b(\\w+\\s*)\\1)", lines, value = TRUE)
cat(out, sep= "\n\n")
#A.1 Goals

#Section 1: Blah Blah Blah

#Section 2: Blah Blah Blah

#A.2 description

数据

lines <- readLines("file.txt") #reading from the file

推荐阅读