从字符串中提取引号中的单词

时间:2021-02-15 17:07:26

标签: r regex

我正在使用 R 从短文本片段中提取单词。具体来说,我想从字符串中提取出现在引号 (") 中的任何单词,但不提取出现在括号 () 中的单词。

例如,我想要 3 个字符串中的第一个“hello”,而不是其他两个:

c('"hello" world', 'hello world', '("hello") world')

原始代码尝试

str_extract(x, '(?<=")[^$]+(?<=")')

2 个答案:

答案 0 :(得分:2)

您可以在 str_extract 中使用带有嵌套环视的正则表达式:

(?<=(?<!\()")[^"]+(?=(?!\))")

RegEx Demo

正则表达式详情:

  • (?<=(?<!\()"):断言我们之前有 " 但没有 ( 之前 "
  • [^"]+:匹配 1+ 个非 "
  • (?=(?!\))"):断言我们在 " 之后有一个 ) 但在 " 之后没有 str_extract(x, '(?<=(?<!\\()")[^"]+(?=(?!\\))")')

代码:

str_extract(x, '(?<=(?<![(])")[^"]+(?=(?![)])")')

或者通过使用字符类避免双重转义:

{{1}}

答案 1 :(得分:1)

我们可以使用正则表达式查看

library(stringr)
ifelse(grepl('\\("', str1), NA,  str_extract(str1, '(?<=")\\w+'))
#[1] "hello" NA      NA    

数据

str1 <- c("\"hello\" world", "hello world", "(\"hello\") world")
相关问题