How can I split string in R from first square bracket and last round bracket?

Viewed 59

I am dealing with legal citations. I want to split the citations into four parts. The citation is in general format as follows: ABC v. DEF [Year] citation data (Authority) So, I want to split it into four parts - ABC v. DEF, Year, citation data, and authority. The problem is that the first part (i.e., ABC v. DEF)might have additional round brackets, while the third part (i.e., citation data) might have additional square and/or round brackets. For example, in this following case

"Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) [2013] 33 taxmann.com 424/60 SOT 118 (URO) (Mum. Trib.)"

The first part is "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation)", second part is "2013", third part is "33 taxmann.com 424/60 SOT 118 (URO)" and the last part is "Mum. Trib." I am unable to come up with the right regex to do this. Can anyone help me with this one?

2 Answers
text <- "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) [2013] 33 taxmann.com 424/60 SOT 118 (URO) (Mum. Trib.)"
pattern <- "(.*?)\\s*\\[(\\d{4})\\]\\s*(.*?)\\s*\\((.*)\\)"

regmatches(text, regexec(pattern, text))
[[1]]
[1] "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) [2013] 33 taxmann.com 424/60 SOT 118 (URO) (Mum. Trib.)"
[2] "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation)"                                                        
[3] "2013"                                                                                                                    
[4] "33 taxmann.com 424/60 SOT 118 (URO)"                                                                                     
[5] "Mum. Trib."

If you want a dataframe:

dat <- data.frame(citation = character(), year = numeric(), data = character(), Authority = character())
strcapture(pattern, text, dat)
                                                          citation year                                data  Authority
1 Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) 2013 33 taxmann.com 424/60 SOT 118 (URO) Mum. Trib.

Use extract:

library(tidyr)
data.frame(txt) %>%
  extract(txt,
          into = c("First", "Sec", "Thrd", "Frth"),
          regex = "(.+)\\[(\\d+)\\](.*)\\((.*)\\)")
                                                              First  Sec                                  Thrd       Frth
1 Lubrizol Corporation, USA v. Asstt. DIT (International Taxation)  2013  33 taxmann.com 424/60 SOT 118 (URO)  Mum. Trib.

The regex part looks scarier than it is: you simply describe the string in full, wrapping those parts that you wish to extract into parentheses (the syntaxt for capturing groups)

Data:

txt <- "Lubrizol Corporation, USA v. Asstt. DIT (International Taxation) [2013] 33 taxmann.com 424/60 SOT 118 (URO) (Mum. Trib.)"
Related