在R中使用正则表达式匹配方括号内的字符串

4
我有许多故事讲述的文字记录,其中有许多重叠的语音,用方括号括起来表示。我想要提取这些重叠的部分。在下面的模拟示例中,
ovl <- c("well [yes right]", "let's go", "oh [  we::ll] i do n't (0.5) know", "erm [°well right° ]", "(3.2)")

这段代码运行良好:
pattern <- "\\[(.*\\w.+])*"
grep(pattern, ovl, value=T) 
matches <- gregexpr(pattern, ovl) 
overlap <- regmatches(ovl, matches)
overlap_clean <- unlist(overlap); overlap_clean
[1] "[yes right]"     "[  we::ll]"      "[°well right° ]"

但在一个更大的文件中,即数据框中,情况就不同了。这是由于模式错误还是由于数据框结构的问题呢?数据框的前六行如下所示:
> head(df)
                                                             Story
1 "Kar:\tMind you our Colin's getting more like your dad every day
2                                             June:\tI know he is.
3                                 Kar:\tblack welding glasses on, 
4                        \tand he turned round and he made me jump
5                                                 \t“O:h, Colin”, 
6                                  \tand then (                  )
2个回答

5

虽然在某些情况下可能有效,但我认为你的模式不正确。我认为应该改成这样:

pattern <- "(\\[.*?\\])"
matches <- gregexpr(pattern, ovl)
overlap <- regmatches(ovl, matches)
overlap_clean <- unlist(overlap)
overlap_clean

[1] "[yes right]"     "[  we::ll]"      "[°well right° ]"

演示

这将匹配并捕获一个括号中的术语,使用Perl延迟点确保我们停在第一个闭合括号处。


是的,您的模式确实更好。至于我的问题,关于数据框,噢好吧,我只是忘记指定列了!所以这个问题也解决了... - Chris Ruehlemann

1

要匹配两个方括号[]之间没有方括号的字符串,请使用

"\\[[^][]*]"

它将在字符串[a[a]中匹配[a],不像\[.*?]模式。

细节

  • \[ - 匹配字符[
  • [^][]* - 一个否定的括号表达式(或字符类),匹配除[]之外的任何0个或多个字符
  • ] - 匹配字符](在字符类/括号表达式之外不需要转义)

请参见Regulex图

enter image description here

查看 R在线演示
ovl <- c("well [yes right]", "let's go", "oh [  we::ll] i do n't (0.5) know", "erm [°well right° ]", "(3.2)")
unlist(regmatches(ovl, gregexpr("\\[[^][]*]", ovl)))
## => [1] "[yes right]"     "[  we::ll]"      "[°well right° ]"

使用stringr::str_extract_all:
library(stringr)
ovl <- c("well [yes right]", "let's go", "oh [  we::ll] i do n't (0.5) know", "erm [°well right° ]", "(3.2)")
unlist(str_extract_all(ovl, "\\[[^\\]\\[]*]"))
## => [1] "[yes right]"     "[  we::ll]"      "[°well right° ]"

由于该模式使用ICU正则表达式库处理,因此您需要在正则表达式模式中转义两个方括号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接