r - 如何提取特定字符串后跟任意数字?
问题描述
我有一个小问题。我有这种格式的文本:
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
所以基本上如何获得任何重复多次并后跟任何可能数字的字符串(相同字符串和不同数字的任何模式)
解决方案
我们可以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
推荐阅读
- node.js - 当要求工作正常时,为什么导入模块会导致“类型'typeof import上的属性不存在”?
- python - escpos 打印机图像未对齐到中心
- python - 是否可以从 Python 的这个列表中计算出一周中每一天收到的所有数字?不明白分裂
- python - 我必须如何在嵌套字典中打印一个值而不会太宽泛
- sql - 别名参考 Date_Diff 天数。需要解析或创建带有日期的临时表?
- php - 为什么我的本地主机显示我的 php 脚本?
- python - Numpy 加载显示所有零的文件
- firebase - Dialogflow 使用 Firebase 连接到 MQTT 代理?
- python - 为什么不能导入子模块?
- c# - 切换到默认大小写