Extract part of string before the first semicolon

Sharath picture Sharath · Apr 20, 2015 · Viewed 7.4k times · Source

I have a column containing values of 3 strings separated by semicolons. I need to just extract the part of the string which comes before the first semicolon.

Type <- c("SNSR_RMIN_PSX150Y_CSH;SP_12;I0.00V50HX0HY3000")

What I want is: Get the first part of the string (till the first semicolon).

Desired output : SNSR_RMIN_PSX150Y_CSH

I tried gsub without success.

Answer

akrun picture akrun · Apr 20, 2015

You could try sub

sub(';.*$','', Type)
#[1] "SNSR_RMIN_PSX150Y_CSH"

It will match the pattern i.e. first occurence of ; to the end of the string and replace with ''

Or use

library(stringi)
stri_extract(Type, regex='[^;]*')
#[1] "SNSR_RMIN_PSX150Y_CSH"