3位数字后删除字符串的一部分

发布于 2025-02-04 22:33:14 字数 326 浏览 1 评论 0原文

我想通过在第一个3位数之后切割每个字符串来代替列表中的字符串。

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

我希望它看起来像

a <- c("MTH314","LB471","PHY472")

我尝试过类似的东西

b <- gsub("[100-999].*","",a)

,但它返回c(“ mth”,“ lb”,“ phy”)没有第一个数字

I would like to substitute the strings in the list by cutting each string after the first 3-digit number.

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

I would like for it to look something like

a <- c("MTH314","LB471","PHY472")

I have tried something like

b <- gsub("[100-999].*","",a)

but it returns c("MTH","LB","PHY") without the first number

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜司空 2025-02-11 22:33:14

基于stringr :: str_remove的可能解决方案:

library(stringr)

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

str_remove(a, "(?<=\\d{3}).*")

#> [1] "MTH314" "LB471"  "PHY472"

A possible solution, based on stringr::str_remove:

library(stringr)

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

str_remove(a, "(?<=\\d{3}).*")

#> [1] "MTH314" "LB471"  "PHY472"
浅浅 2025-02-11 22:33:14
c("MTH314PHY410","LB471LB472","PHY472CHM141") %>% 
    stringr::str_extract('.+?\\d{3}')
[1] "MTH314" "LB471"  "PHY472"
c("MTH314PHY410","LB471LB472","PHY472CHM141") %>% 
    stringr::str_extract('.+?\\d{3}')
[1] "MTH314" "LB471"  "PHY472"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文