R:查找字符串中的最后一个点 [英] R: Find the last dot in a string

查看:43
本文介绍了R:查找字符串中的最后一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中,是否有比以下找到字符串中最后一个点的位置更好/更简单的方法?

In R, is there a better/simpler way than the following of finding the location of the last dot in a string?

x <- "hello.world.123.456"
g <- gregexpr(".", x, fixed=TRUE)
loc <- g[[1]]
loc[length(loc)]  # returns 16

这会找到字符串中的所有点,然后返回最后一个,但看起来相当笨拙.我尝试使用正则表达式,但没有走多远.

This finds all the dots in the string and then returns the last one, but it seems rather clumsy. I tried using regular expressions, but didn't get very far.

推荐答案

这对您有用吗?

x <- "hello.world.123.456"
g <- regexpr("\\.[^\\.]*$", x)
g

  • \. 匹配一个点
  • [^\.] 匹配除点以外的所有内容
  • * 指定前面的表达式(除了点以外的所有内容)可以出现 0 次到无限次
  • $ 标记字符串的结尾.
    • \. matches a dot
    • [^\.] matches everything but a dot
    • * specifies that the previous expression (everything but a dot) may occur between 0 and unlimited times
    • $ marks the end of the string.
    • 把所有东西放在一起:找到一个点,后面跟着一个点,直到字符串结束.R 要求 \ 被转义,因此 \\ 在上面的表达式中.请参阅 regex101.com 以试验正则表达式.

      Taking everything together: find a dot that is followed by anything but a dot until the string ends. R requires \ to be escaped, hence \\ in the expression above. See regex101.com to experiment with regex.

      这篇关于R:查找字符串中的最后一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆