提取字符串中的部分如何做?

huangapple go评论66阅读模式
英文:

How to extract part from string?

问题

I need to extract whatever is between \\\ and _proj.

我需要提取在 \\\_proj 之间的内容。

英文:

If I have this string:

bb=c("\\dat\\Bjkjgf_Yloiut_dsezr_proj_111_999.txt","\\dat\\Bjkjgf_Yloezr_proj_111_999.txt")

I need to extract whatever between \\ and _proj

i can do this, but will work for one and not the other:

substr(bb, 1, 15)

the expected output

Bjkjgf_Yloiut_dsezr,Bjkjgf_Yloezr

答案1

得分: 1

使用 gsub

gsub(".*\\\\|_proj.*", "", bb)
[1] "Bjkjgf_Yloiut_dsezr" "Bjkjgf_Yloezr"
英文:

Using gsub

gsub(".*\\\\|_proj.*", "", bb)
[1] "Bjkjgf_Yloiut_dsezr" "Bjkjgf_Yloezr"

答案2

得分: 0

使用regmatches:

sapply(regmatches(bb, regexec("dat\\\\(.*)_proj", bb)), `[`, 2)
#[1] "Bjkjgf_Yloiut_dsezr" "Bjkjgf_Yloezr"   

或者使用stringr::str_match:

stringr::str_match(bb, "dat\\\\(.*)_proj")[, 2]
英文:

With regmatches:

sapply(regmatches(bb, regexec("dat\\\\(.*)_proj", bb)), `[`, 2)
#[1] "Bjkjgf_Yloiut_dsezr" "Bjkjgf_Yloezr"   

Or stringr::str_match:

stringr::str_match(bb, "dat\\\\(.*)_proj")[, 2]

huangapple
  • 本文由 发表于 2023年4月10日 19:17:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定