Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on comma following a specific word

Tags:

regex

r

I have a vector with names, e.g.:

names <- "Jansen, A., Karel, A., Jong, A. de, Pietersen, K."

And I want to split this per name. In this case, I need to split the vector on ., and the comma following de (That name would be A. De Jong, which is typical in Dutch).

Right now I do:

 strsplit(names,split="\\.\\,|\\<de\\>,")

But this also removes the de from the name:

[[1]]
[1] "Jansen, A"      " Karel, A"      " Jong, A. "     " Pietersen, K."

How can I obtain the following as result?

[[1]]
[1] "Jansen, A"      " Karel, A"      " Jong, A. de"     " Pietersen, K."
like image 780
Sacha Epskamp Avatar asked Jan 19 '23 04:01

Sacha Epskamp


2 Answers

polishchuk's regex needs two modifications to make it work in R.

Firstly, the backslash needs escaping. Secondly, the call to strsplit needs the argument perl = TRUE to enable lookbehind.

strsplit(names, split = "\\.,|(?<=de)", perl = TRUE)

gives the answer Sacha asked for.

Notice though that this still includes a dot in de Jong's name, and it isn't extensible to alternatives like van, der, etc. I suggest the following alternative.

names <- "Jansen, A., Karel, A., Jong, A. de, Pietersen, K., Helsing, A. van"
#split on every comma
first_last <- strsplit(names, split = ",")[[1]]
#rearrange into a matrix with the first column representing last names, 
#and the second column representing initials
first_last <- matrix(first_last, byrow = TRUE, ncol = 2) 
#clean up: remove leading spaces and dots
first_last <- gsub("^ ", "", first_last)
first_last <- gsub("\\.", "", first_last)
#combine columns again
apply(first_last, 1, paste, collapse = ", ")
like image 97
Richie Cotton Avatar answered Jan 28 '23 20:01

Richie Cotton


Try this regex: \.,|(?<=de), with look-behind.

It will match:

Jansen, A., Karel, A., Jong, A. de, Pietersen, K.

like image 31
Kirill Polishchuk Avatar answered Jan 28 '23 22:01

Kirill Polishchuk