0

I'm trying to extract a substring dynamically from the right of a character.

string<- adcde?7890 desired substring: 7890

in order to achieve this I want to be able to determine the position of the "?" within each character string, where in this example the "?" would be the 6th character.

In the end my code would look something like this:

substr("location of'?'"+1 , str_length(string))

I just need a function which will show the position of the "?" within my string.

Luca Foerster
  • 93
  • 1
  • 2
  • 4

2 Answers2

2

We can use str_locate to find the location of the character ?. It is a regex metacharacter, so we can place it in square brackets (or escape) to evaluate it as the literal character

library(stringr)
substr(string, str_locate(string, "[?]")[1] + 1, str_length(string))
#[1] "7890"

or using only base R, we can find the matching position with regexpr and use that as the start position in substring

substring(string, regexpr("[?]", string)+1)
#[1] "7890"

Or use str_extract

str_extract(string, "(?<=[?])\\d+")
#[1] "7890"

data

string <- 'adcde?7890'
akrun
  • 874,273
  • 37
  • 540
  • 662
0

To do this in base R:

substr(string,regexpr("\\?",string)+1,nchar(string)) # You use \\ since ? is a special character  
[1] "7890"

But you can avoid all this and just use sub

  sub(".*\\?","",string)
 [1] "7890"
Onyambu
  • 67,392
  • 3
  • 24
  • 53