提取文本中的第一个括号,并附带一些观察结果的条件



我有一些数据,看起来像:

# 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 …

我正试图从LP列的文本中提取一些信息。

我想提取以下内容:

row1=(纽约证券交易所-美国证券交易所:SYRG(第2行=(FB(第3行=(PXD(row4=…row5=…

提取的"规则"是这样的。

在第1行和第3行中,我想提取第一个双括号--之后的第一个括号()。在第2行中,我只想提取第一个()。在第4行和第5行中,忽略。

数据:

structure(list(grp = c("4999", "9122", "161", "6047", "9585"), 
LP = c(" PLATTEVILLE, Colo., Dec. 30, 2011 /PRNewswire/ -- Synergy Resources Corporation (NYSE Amex: SYRG) ("Synergy Resources"), a domestic oil and gas exploration and production company focused in the Denver-Julesburg Basin ("D-J Basin"), announced today that the underwriters have closed on their purchase of an additional 1,909,090 shares of Synergy Resources common stock at a public offering price of $2.75 per share. The shares were sold to underwriters to cover over-allotments in connection with the previously announced public offering of 12,727,273 shares of Synergy Resources' common stock that closed on December 21, 2011. The underwriters had previously notified Synergy Resources that they were exercising their over-allotment option in full. Synergy Resources expects net proceeds from the exercise of the over-allotment option to be approximately $4,900,000. Synergy Resources intends to use the net proceeds from the offering for its development drilling program in the Wattenberg Field.n    ", 
" 14:22 ET - Facebook (FB) has hired Campbell Brown, a former anchor for CNN and NBC, to run news partnerships. Brown will pitch and solicit publishers' feedback on products like Instant Articles and Facebook Live, but she won't decide how FB should handle sensitive and newsworthy content, like the 30-minute live video posted this week showing a Chicago man being tortured. FB has a wary relationship with media outlets. FB's dominance in digital ads has hurt the economics of many publishers. Users and media outlets have also criticized FB for allowing the spread of fake news on its platform in recent months. (deepa.seetharaman@wsj.com; @dseetharaman)n    ", 
" DALLAS (Dow Jones)--Pioneer National Resources Co. (PXD) sold 20.5 million barrels of oil equivalent reserves, or 2% of its total reserves, for total proceeds of $593 million.  nnPioneer also said it expects to report fourth-quarter earnings of 66 cents to 69 cents a share after having produced 198,000 barrels of oil equivalent per day during the quarter.  n    ", 
" n nTOP STORIES n nUS HOUSING, MANUFACTURING SHOW STRENGTH AT YEAR END n   nnTwo sore spots in the U.S. economy show some strength at the end of 2006, with demand rising for expensive manufactured goods and new homes. New-home sales rise 4.8% in December to 1.120 million, but demand for whole year takes its biggest tumble since 1990, sliding 17% to 1.061 million. Separately, orders for durables advance by 3.1% last month to $221.87 billion.  n    ", 
" DuPont Co., looking to wrap up its merger with Dow Chemical Co., said its sales rose as the science company benefited from a change in the timing of seed deliveries.nnThe Delaware-based company also gave a downbeat outlook for the current quarter, projecting adjusted earnings of about $1.26 a share, below the Thomson Reuters consensus of $1.31 a share. As reported, DuPontexpects earnings to fall about 5% due to merger related expenses.n    "
), RE = c(" usa : United States | usco : Colorado | usw : Western U.S. | namz : North America    ", 
" usa : United States | namz : North America    ", " usa : United States | ustx : Texas | namz : North America | uss : Southern U.S.    ", 
" usa : United States | namz : North America    ", " usde : Delaware | namz : North America | usa : United States | uss : Southern U.S.    "
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-5L))

我们可以使用str_match:

str_match(df$LP, '--?.*?(\(.*?\))')[, 2]
#[1] "(NYSE Amex: SYRG)" "(FB)"  "(PXD)"  NA    NA 

这将捕获前面有可选'--'的圆括号中的所有内容。

如果行有"--",那么在"--"之后查找第一个括号,否则查找的第一个括号

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_firststr_remove一起使用

library(stringr)
library(stringi)
str_remove(stri_extract_first(df1$LP, regex = "--?[^(]+\([^\)]+\)"), 
"^[^\(]+")
#[1] "(NYSE Amex: SYRG)" "(FB)"              "(PXD)"             NA                  NA  

最新更新