Rajarshi Bhadra
Rajarshi Bhadra

Reputation: 1944

Extract string using stringr

I have a string "BTL_OTM_TLS_TTL_ACQ_0.0.0|Fixed" from where I want to extract "BTL_OTM_TLS_TTL_ACQ".

However I am getting "BTL_OTM_TLS_TTL_ACQ" "|". I have used stringr and I have provided the code below. Any help will be greatly appreciated.

> k
[1] "BTL_OTM_TLS_TTL_ACQ_0.0.0|Fixed"
> str_extract(k, "(_)[0-9](.)+")
[1] "_0.0.0|Fixed"
> strsplit(as.character(k),str_extract(as.character(k),"(_)[0-9](.)+"))
[[1]]
[1] "BTL_OTM_TLS_TTL_ACQ" "|"

Upvotes: 1

Views: 180

Answers (1)

akrun
akrun

Reputation: 886978

You can try sub from base R

 sub('_\\d.*', '', k)
 #[1] "BTL_OTM_TLS_TTL_ACQ"

Or using lookarounds with str_extract

 library(stringr)
 str_extract(k, perl('.*(?=_[0-9])'))
 #[1] "BTL_OTM_TLS_TTL_ACQ"

Or

strsplit(k, '_[0-9]+.*$')[[1]]
#[1] "BTL_OTM_TLS_TTL_ACQ"

Update

If we need to extract 0.0.0, one option is

gsub('^[^0-9]*|\\|.*$', '', k)
#[1] "0.0.0"

data

k <- "BTL_OTM_TLS_TTL_ACQ_0.0.0|Fixed"

Upvotes: 6

Related Questions