首页 > 解决方案 > 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]

标签: rregexstringr

解决方案


可以使用空白字符选择选项“ \\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"

推荐阅读