r - str_match_all 带换行符?
问题描述
这会提取 'here' 和 'text' 之间的文本
test <- "here is some text"
str_match_all(test, "here(.*?)text")
# [[1]]
# [,1] [,2]
# [1,] "here is some text" " is some "
但是换行符会干扰 - 我们如何提取“这里”和“文本”之间的所有内容,包括换行符?
test <- "here
is
some
text"
str_match_all(test, "here(.*?)text")
# [[1]]
# [,1] [,2]
解决方案
可以使用空白字符选择选项“ \\s ”。此字符串“ (.|\\s) ”表示任何字符或空格。
str_match_all(test, "here((.|\\s)*?)text")
[[1]]
[,1] [,2] [,3]
[1,] "here \nis \nsome \ntext" " \nis \nsome \n" "\n"
编辑
这是另一种效果更好的形式(只有两部分,但最后仍然有一个额外的换行符):
str_match_all(test, "here([[[:alnum:]]|[[:space:]]]+?)text")
[[1]]
[,1] [,2]
[1,] "here \nis \nsome \ntext" " \nis \nsome \n"
推荐阅读
- javascript - 分配调用者的匿名注入方法工厂名称
- mysql - 可以指示 MySQL/Postgres 忽略索引或列吗?
- javascript - 如何制作一个每次刷新时都会更改内容的简单网站?
- css - FlightGear“致命异常无效字符串位置”运行 NASA 的 MATLAB 内置 HL-20 模型
- python - 广播和连接不规则张量
- java - 如何将从函数获得的两个值传递给相应的变量
- scala - Shapeless:提取注解参数化的case case字段值
- java - 流用于从带有计数器的列表中进行地图计算
- python - 形状未与 Python 对齐
- python - 在 Pandas DataFrame 中矢量化行级匹配操作