grep - how to return only matched part of string on a column

Viewed 56

I have a dataframe that looks like this:

RandomCol raw
blah <div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div>
blahblah <title>WY-12blah.13-10K </title>

I would like to extract any font size values where they exist, using regex; I would like output that looks like this:

RandomCol raw fontsize
blah <div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div> font-size:9pt
blahblah <title>WY-12blah.13-10K </title>

The closest attempt I've made is this code:

df$fontsize <- ""
df$fontsize[grepl("font-size:", df$raw,ignore.case = TRUE)] <- grep("font-size:(.*?);",df$raw,ignore.case = TRUE,value=TRUE)

However, it gives me this:

RandomCol raw fontsize
blah <div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div> <div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div>
blahblah <title>WY-12blah.13-10K </title>

How do I tweak it to return only the part that matched? Thanks

3 Answers

You can use regexpr with regmatches:

regmatches(x, regexpr("font-size:(.*?);", x, ignore.case = TRUE))
#[1] "font-size:9pt;"

Data:

x <- '<div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div>'

You can use stringr str_extract for this

t <- '<div style="line-height:174%;text-align:left;font-size:9pt;"><font style="font-family:inherit;font-size:9pt;font-style:italic;font-weight:bold;">We have a history of losses, and we cannot assure you that we will achieve profitability.</font></div>'

# for the first occurence
stringr::str_extract(t, "font-size:(.*?);")
#> [1] "font-size:9pt;"


#for every occurence
stringr::str_extract_all(t, "font-size:(.*?);")
#> [[1]]
#> [1] "font-size:9pt;" "font-size:9pt;"

Created on 2021-02-17 by the reprex package (v0.3.0)

You can use gsuband backreference:

gsub(".*(font-size:\\d+pt).*", "\\1", t)
[1] "font-size:9pt"
Related