How to extract string between the first occurrence of a character and first occurrence of another character?

Viewed 135
reprEx <- "jhbasdjjk\n ELECTRONIC WITHDRAWALS kd; jjjjj ELECTRONIC WITHDRAWALS cont. jjjajhahgab OTHER WITHDRAWALS"

I would like to extract all text between the first occurrence of ELECTRONIC WITHDRAWALS and OTHER WITHDRAWALS. the result I want would look like the following:

desiredResult <- "kd; jjjjj ELECTRONIC WITHDRAWALS cont. jjjajhahgab"
1 Answers

We can use sub to capture the characters between those substring and replace with the back reference of the captured group

sub(".*\n ELECTRONIC WITHDRAWALS (.*) OTHER WITHDRAWALS", "\\1", reprEx)
#[1] "kd; jjjjj ELECTRONIC WITHDRAWALS cont. jjjajhahgab"
Related