Replace last occurence of regexp in a string which has new lines (replace-regexp-in-string in Emacs)

Viewed 61

I have this expression which I've parsed in Emacs:

mtcars %>%
head() %>%
select(mpg, cyl) %>%"

I want to replace the last %>% with whatever number of white spaces it might have after with nothing. So this works:

(replace-regexp-in-string "%>% *$" "" "mtcars %>% head() %>% select(mpg, cyl) %>%")

and returns mtcars %>% head() %>% select(mpg, cyl)

But what I actually have is this:

(replace-regexp-in-string "%>% *$" "" "mtcars %>%
head() %>%
select(mpg, cyl) %>%")

which returns a replacement of all %>% instead of the last:

mtcars
head()
select(mpg, cyl)

Anyone know how to achieve that with a string with new lines rather than in a single one?

1 Answers

. doesn't match a newline. Tell the regex that newlines can also precede the the %>%, so the \\1 will match all the previous lines:

(replace-regexp-in-string "\\(\\(.\\|\n\\)*\\)%>% *$" "\\1" "mtcars %>%
head() %>%
select(mpg, cyl) %>%")
Related