How to extract everything until first occurrence of pattern

旧时模样 提交于 2019-12-04 01:51:05

To get L0, you may use

> library(stringr)
> str_extract("L0_123_abc", "[^_]+")
[1] "L0"

The [^_]+ matches 1 or more chars other than _.

Also, you may split the string with _:

x <- str_split("L0_123_abc", fixed("_"))
> x
[[1]]
[1] "L0"  "123" "abc"

This way, you will have all the substrings you need.

The same can be achieved with

> str_extract_all("L0_123_abc", "[^_]+")
[[1]]
[1] "L0"  "123" "abc"

The regex lookaround should be

str_extract("L0_123_abc", ".+?(?=_)")
#[1] "L0"

Using gsub...

gsub("(.+?)(\\_.*)", "\\1", "L0_123_abc")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!