1

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" "|"

1 Answer 1

6

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"
Sign up to request clarification or add additional context in comments.

2 Comments

is there any way I can extract 0.0.0 out of the expression??
Try gsub('^[^0-9]*|\\|.*$', '', k)#[1] "0.0.0"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.