我有一个大字符串,我想匹配/提取具有开始和结束搜索模式的模式。如何在 R 中完成?
字符串示例:
big_string <- "read.csv(\"http://company.com/students.csv\", header = TRUE)","solution":"# Preview students with str()\nstr(students)\n\n# Coerce Grades to character\nstudents$Grades <- read.csv(\"http://company.com/students_grades.csv\", header = TRUE)"
我想在此实例中提取 url 组件。因此,模式以 http
开头并以 .csv
结尾或任何扩展名(如果可能)。
http://company.com/students.csv
http://company.com/students_grades.csv
我多次尝试使用 gregexpr
都不走运提取模式。有人可以帮忙想出一种在 R 中执行此操作的方法吗?
最佳答案
stringr 包非常适合这种类型的应用程序:
library(stringr)
big_string <- 'read.csv(\"http://company.com/students.csv\", header = TRUE)","solution":"# Preview students with str()\nstr(students)\n\n# Coerce Grades to character\nstudents$Grades <- read.csv(\"http://company.com/students_grades.csv\", header = TRUE)'
results<-unlist(str_extract_all(big_string, "http:.+csv"))
搜索模式是以“http:”开头且至少有 1 个字符并以“csv”结尾的字符串
关于r - 如何使用 R 在大字符串中提取模式(开始和结束)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149872/