如何使用正则表达式提取字符串中花括号{}内的内容列表?
Hey there! Let's figure out how to extract those curly-braced phrases from your R string into a list. I'll show you two straightforward ways to do this—one using a popular tidyverse package, and another with base R so you don't need to install anything extra.
Method 1: Using the stringr Package (Recommended for Simplicity)
The stringr package makes regex tasks in R super intuitive. First, make sure you have it installed and loaded:
install.packages("stringr") library(stringr)
Now let's process your string:
str1 <- "Hello {can you please} {extract this}" # Extract all text inside curly braces extracted_values <- str_extract_all(str1, "\\{(.*?)\\}")[[1]] # Remove the curly braces from each extracted item extracted_values <- str_remove_all(extracted_values, "\\{|\\}") # Convert to a list (if you need a list specifically, not just a character vector) extracted_list <- as.list(extracted_values)
Quick Regex Breakdown:
\\{and\\}: We escape the curly braces because they're special characters in regex—this tells R to match the literal{and}.(.*?): The.*?is a non-greedy match, meaning it grabs everything until the first closing curly brace it finds. This prevents it from accidentally merging both phrases into one match.
Running this code will give you a list where extracted_list[[1]] is "can you please" and extracted_list[[2]] is "extract this".
Method 2: Using Base R (No Extra Packages Needed)
If you prefer to stick with base R tools, you can combine gregexpr() and regmatches() to get the same result:
str1 <- "Hello {can you please} {extract this}" # Find the positions of all curly-braced patterns match_positions <- gregexpr("\\{(.*?)\\}", str1) # Extract the matching text extracted_text <- regmatches(str1, match_positions)[[1]] # Strip out the curly braces extracted_text <- gsub("\\{|\\}", "", extracted_text) # Convert to a list extracted_list <- as.list(extracted_text)
This works exactly the same way as the stringr method—you'll end up with the same list of phrases.
A quick note: This approach assumes you don't have nested curly braces in your string (like {text {inside} more text}). If you did, we'd need a more complex regex, but your example doesn't have that, so this is perfect.
内容的提问来源于stack exchange,提问作者LotsofQuestions

