Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers from a string separated by "-" with their signs

Tags:

regex

r

The string I have is separated by dash with positive and negative numbers. For example, two strings that I have look like:

"1-2--3"
"-1-2--3"

and I want to extract "1", "2", "-3" from string 1

and to have "-1", "2", "-3" from string 2

How can I do it in R?

like image 672
Gillian Avatar asked Mar 04 '23 12:03

Gillian


1 Answers

You can use stringr for easy splitting with a positive look behind

library(stringr)
x <- c("1-2--3", "-1-2--3")
str_split(x, "(?<=\\d)-")

# [[1]]
# [1] "1"  "2"  "-3"
# 
# [[2]]
# [1] "-1" "2"  "-3"

This splits the string at each dash that follows a number.

As pointed out by @IceCreamToucan, this would work fine with the base R strsplit function as well if you set perl=TRUE

strsplit(x, "(?<=\\d)-", perl=TRUE)
like image 177
MrFlick Avatar answered May 18 '23 20:05

MrFlick