R 根据一些观察结果提取文本中的第一个括号
我有一些数据看起来像:R 根据一些观察结果提取文本中的第一个括号,r,R,我有一些数据看起来像: # A tibble: 5 x 3 grp LP RE <chr> <chr> <chr>
# A tibble: 5 x 3
grp LP RE
<chr> <chr> <chr>
1 4999 " PLATTEVILLE, Colo., Dec. 30, 2011 /PRNewswire/ -- Sy… " usa : United States | usco : Colorado | us…
2 9122 " 14:22 ET - Facebook (FB) has hired Campbell Brown, a… " usa : United States | namz : North America…
3 161 " DALLAS (Dow Jones)--Pioneer National Resources Co. (… " usa : United States | ustx : Texas | namz …
我们可以使用str_匹配:
这将捕获圆括号中的所有内容,并在其前面加上可选的“-” 我们可以使用str\u匹配:
这将捕获圆括号中的所有内容,并在其前面加上可选的“-” 如果行中有“-”,则查找“-”之后的第一个括号,否则查找第一个括号
lapply(dat$LP,
function(x){
# split the text where there is --
x_0 <- (x %>% strsplit('--'))[[1]]
# if the text contains the string '--'
# then length(x_0) is more than 1
if(length(x_0) > 1){
# remove the first part of the split, paste the rest back together
# meaning: start looking for the brackets after '--'
x <- paste(x_0[-1], collapse = ' ')
} # else we'll look for the brackets in the full string
# find where there's brackets in the text
pos <- gregexpr("\\(.*?\\)", x)[[1]]
# get the position of the first occurence
start <- pos[1]
# get the length of the first occurence
leng <- attr(pos, "match.length")[1]
# extract the string
res <- substr(x, start, start+leng)
return(res)
})
如果行中有“-”,那么在“-”之后查找第一个括号,否则查找第一个括号
lapply(dat$LP,
function(x){
# split the text where there is --
x_0 <- (x %>% strsplit('--'))[[1]]
# if the text contains the string '--'
# then length(x_0) is more than 1
if(length(x_0) > 1){
# remove the first part of the split, paste the rest back together
# meaning: start looking for the brackets after '--'
x <- paste(x_0[-1], collapse = ' ')
} # else we'll look for the brackets in the full string
# find where there's brackets in the text
pos <- gregexpr("\\(.*?\\)", x)[[1]]
# get the position of the first occurence
start <- pos[1]
# get the length of the first occurence
leng <- attr(pos, "match.length")[1]
# extract the string
res <- substr(x, start, start+leng)
return(res)
})
我们可以先使用stri_extract_和str_remove
我们可以先使用stri_extract_和str_remove
lapply(dat$LP,
function(x){
# split the text where there is --
x_0 <- (x %>% strsplit('--'))[[1]]
# if the text contains the string '--'
# then length(x_0) is more than 1
if(length(x_0) > 1){
# remove the first part of the split, paste the rest back together
# meaning: start looking for the brackets after '--'
x <- paste(x_0[-1], collapse = ' ')
} # else we'll look for the brackets in the full string
# find where there's brackets in the text
pos <- gregexpr("\\(.*?\\)", x)[[1]]
# get the position of the first occurence
start <- pos[1]
# get the length of the first occurence
leng <- attr(pos, "match.length")[1]
# extract the string
res <- substr(x, start, start+leng)
return(res)
})
library(stringr)
library(stringi)
str_remove(stri_extract_first(df1$LP, regex = "--?[^(]+\\([^\\)]+\\)"),
"^[^\\(]+")
#[1] "(NYSE Amex: SYRG)" "(FB)" "(PXD)" NA NA