【问题标题】:regex - extract strings between curly braces without the curly braces正则表达式 - 在没有大括号的大括号之间提取字符串
【发布时间】:2020-11-30 20:20:12
【问题描述】:

我有以下字符向量:

text_test <- c(
  "\\name{function_name}",
  "\\title{function_title}",
  "The function \\name{function_name} is used somewhere"
)

我想提取花括号之间的单词,即function_namefunction_title。我试过这个:

stringr::str_extract(text_test, '\\{[^\\}]*\\}')

但这也会提取花括号。

我有两个问题:

  • 如何修改此正则表达式以排除花括号?

  • 如何在基础 R 中做到这一点?

【问题讨论】:

标签: r regex


【解决方案1】:

我们可以使用正则表达式环视来匹配{ 作为环视后跟一个或多个不是} 的字符。

stringr::str_extract(text_test, '(?<=\\{)[^\\}]+')
#[1] "function_name"  "function_title" "function_name" 

正则表达式匹配一个或多个不是} ([^\\}]+) 的字符,它跟在{ 之后(正则表达式环视((?&lt;=\\{)


base R中,我们可以使用regmatches/regexpr

regmatches(text_test, regexpr("(?<=\\{)[^\\}]+", text_test, perl = TRUE))
#[1] "function_name"  "function_title" "function_name" 

【讨论】:

  • 嗨,您能详细说明一下您使用的正则表达式吗?正则表达式的新手(像我一样)很难理解
猜你喜欢
  • 2011-07-17
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多