Catiger3331
Catiger3331

Reputation: 641

Regexpr not working as expected

For the following string <10.16;13.05) I want to match only the first number (sometimes the first number does not exist, i.e. <;13.05)). I used the following regular expression:

grep("[0-9]+\\.*[0-9]*(?=;)","<10.16;13.05)",value=T,perl=T)

However, the result is not "10.16" but "<10.16;13.05)". Could anyone please help me with this one? Thanks.

Upvotes: 1

Views: 68

Answers (2)

Sotos
Sotos

Reputation: 51592

You could also use strsplit here with minimum regex, i.e.

x <- '<10.16;13.05)'
as.numeric(gsub('<(.*)', '\\1', unlist(strsplit(x, ';', fixed = TRUE))[1]))
#[1] 10.16

x <- '<;13.05)'
as.numeric(gsub('<(.*)', '\\1', unlist(strsplit(x, ';', fixed = TRUE))[1]))
#[1] NA

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76621

I believe you are using the wrong regex function. grep just tells you whether the patern was found, it does not extract it.

Try instead

regmatches("<10.16;13.05)", regexpr("\\d*\\.\\d*", "<10.16;13.05)"))

Upvotes: 1

Related Questions