如何提取所有内容直到第一次出现模式 [英] How to extract everything until first occurrence of pattern
问题描述
我正在尝试使用 R 中的 stringr 包来提取字符串中的所有内容,直到第一次出现下划线.
I'm trying to use the stringr package in R to extract everything from a string up until the first occurrence of an underscore.
我的尝试
str_extract("L0_123_abc", ".+?(?<=_)")
> "L0_"
关闭但没有雪茄.我如何得到这个?另外,理想情况下,我想要一些易于扩展的东西,以便我可以在第 1 条和第 2 条下划线之间获取信息,并在第 3 条下划线之后获取信息.
Close but no cigar. How do I get this one? Also, Ideally I'd like something that's easy to extend so that I can get the information in between the 1st and 2nd underscore and get the information after the 3rd underscore.
推荐答案
要获得 L0
,可以使用
> library(stringr)
> str_extract("L0_123_abc", "[^_]+")
[1] "L0"
[^_]+
匹配 1 个或多个 _
以外的字符.
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.
同样可以用
> str_extract_all("L0_123_abc", "[^_]+")
[[1]]
[1] "L0" "123" "abc"
这篇关于如何提取所有内容直到第一次出现模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!