【问题标题】:Replace last occurence of regexp in a string which has new lines (replace-regexp-in-string in Emacs)替换具有新行的字符串中最后一次出现的正则表达式(在 Emacs 中替换正则表达式)
【发布时间】:2021-04-29 02:46:07
【问题描述】:

我有这个在 Emacs 中解析过的表达式:

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

我想将最后一个%>% 替换为之后 中可能包含的任意数量的空格nothing。所以这行得通:

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

并返回mtcars %>% head() %>% select(mpg, cyl)

但我实际上拥有的是这样的:

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

返回所有 %>% 而不是最后一个的替换:

mtcars
head()
select(mpg, cyl)

任何人都知道如何使用带有新行而不是单个行的字符串来实现这一点?

【问题讨论】:

    标签: regex replace emacs


    【解决方案1】:

    . 不匹配换行符。告诉正则表达式换行符也可以在%>% 之前,所以\\1 将匹配前面的所有行:

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

    【讨论】:

    • 我应该在一个单独的问题中问这个问题,但万一这对你来说很简单。我希望上述工作(确实如此),但只要最后一行没有 %>%,它应该保持原样。所以这个:(replace-regexp-in-string "\\(\\(.\\|\n\\)*\\)%>% *$" "\\1" "mtcars %>% head() %>% select(mpg, cyl) %>% arrange(cyl)") 不应该删除任何 %>%。我尝试通过调整正则表达式以仅替换 %>% *$ 直到字符串末尾来强制执行此操作,但它会不断删除最后一个 %>%。任何提示都会很棒!
    • @cimentadaj:将$(行尾)替换为\\'(字符串尾)。
    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2015-11-30
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多