删除最后一次出现的字符

Tyl*_*ker 15 regex r

今天talkstats.com上出现了一个问题,其中海报想要使用正则表达式(不是strsplit)删除字符串的最后一段时间.我试图这样做,但没有成功.

N <- c("59.22.07", "58.01.32", "57.26.49")

#my attempts:
gsub("(!?\\.)", "", N)
gsub("([\\.]?!)", "", N)
Run Code Online (Sandbox Code Playgroud)

我们怎样才能删除字符串中的最后一个句点来获取:

[1] "59.2207" "58.0132" "57.2649"
Run Code Online (Sandbox Code Playgroud)

flo*_*del 23

也许这看起来好一点:

gsub("(.*)\\.(.*)", "\\1\\2", N)
[1] "59.2207" "58.0132" "57.2649"
Run Code Online (Sandbox Code Playgroud)

因为它是贪婪的,所以第一个(.*)将匹配到最后一个.并存储它\\1.第二个(.*)将匹配最后一个.并存储它的所有内容\\2.

从某种意义上说,这是一个通用的答案,您可以用\\.您选择的任何字符替换它以删除该字符的最后一次出现.这只是一个替代品!

你甚至可以这样做:

gsub("(.*)\\.", "\\1", N)
Run Code Online (Sandbox Code Playgroud)


Roh*_*ain 12

你需要这个正则表达式: -

[.](?=[^.]*$)
Run Code Online (Sandbox Code Playgroud)

并用空字符串替换它.

所以,应该是这样的: -

gsub("[.](?=[^.]*$)","",N,perl = TRUE)
Run Code Online (Sandbox Code Playgroud)

说明: -

[.]         // Match a dot
(?=         // Followed by
    [^.]    // Any character that is not a dot.
     *      // with 0 or more repetition
     $      // Till the end. So, there should not be any dot after the dot we match.
)  
Run Code Online (Sandbox Code Playgroud)

因此,只要a dot(.)在前瞻中匹配,匹配就会失败,因为,dot在当前点之后的某处,模式是匹配的.


Ric*_*ven 5

我相信你现在知道这一点,因为你stringi在你的包中使用过,但你可以简单地做

N <- c("59.22.07", "58.01.32", "57.26.49")

stringi::stri_replace_last_fixed(N, ".", "")
# [1] "59.2207" "58.0132" "57.2649"
Run Code Online (Sandbox Code Playgroud)