-1

In the string I am trying to extract the 0.4% that comes after 12 month(s)\n$500

I search for 12 month(s)\n$500 and then grab number dot number that comes after.

From here, "To match a literal “$” or “^”, you need to escape them, $, and ^." But when I do that, I get the error:

Error: '\$' is an unrecognized escape in character string starting ""(?<=12 month(s)\\n\$"

What am I doing wrong?

x <- "Term Minimum investment Rate Interest type Get this GIC\n3 month(s)\n$500 0.15% Simple\nChoose this GIC\n6 month(s)\n$500 0.25% Simple\nChoose this GIC\n9 month(s)\n$500 0.30% Simple\nChoose this GIC\n12 month(s)\n$500 0.40% Simple\nChoose this GIC\n18 month(s)\n$500 0.50% Simple\nChoose this GIC\n18 month(s)\n$500 0.50% Compound\nChoose this GIC"

as.numeric(stringr::str_extract(x, "(?<=12 month(s)\\n\$500)\\d\\.\\d{1,}"))
ixodid
  • 2,180
  • 1
  • 19
  • 46

1 Answers1

0

You need to escape with double backslash in R. (\\). Also you need to escape opening and closing round brackets (()).

as.numeric(stringr::str_extract(x,"(?<=12 month\\(s\\)\n\\$500\\s)\\d\\.\\d{1,}"))
#[1] 0.4

In base R with sub :

as.numeric(sub('.*12 month\\(s\\)\n\\$500\\s(\\d\\.\\d{1,}).*', '\\1', x))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Although my question is basic I don't think it's reasonable that I would have searched for the moderator's suggestion. I had forgotten that brackets need to be escaped. Thank-you @Ronak Shah for the speedy response. – ixodid Nov 15 '20 at 01:38