Remove last occurrence of character

前端 未结 4 1442
醉梦人生
醉梦人生 2021-02-07 11:58

A question came across talkstats.com today in which the poster wanted to remove the last period of a string using regex (not strsplit). I made an attempt to do thi

4条回答
  •  忘掉有多难
    2021-02-07 12:13

    You need this regex: -

    [.](?=[^.]*$)
    

    And replace it with empty string.

    So, it should be like: -

    gsub("[.](?=[^.]*$)","",N,perl = TRUE)
    

    Explanation: -

    [.]         // 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.
    )  
    

    So, as soon as a dot(.) is matched in the look-ahead, the match is failed, because, there is a dot somewhere after the current dot, the pattern is matching.

提交回复
热议问题