r - How do I extract the first number that occurs after a matching pattern -


consider these examples:

examples <- c(   "abc foo",   "abc foo 17",   "0 abc defg foo 5 121",   "abc 12 foo defg 11" ) 

here return first number occurs after "foo". in case: na, 17, 5, 11. how can this? tried using look-behind, no luck.

library(stringr) str_extract(examples, "(?<=foo.*)[0-9]+")  error in stri_extract_first_regex(string, pattern, opts_regex = opts(pattern)) :    look-behind pattern matches must have bounded maximum length. (u_regex_look_behind_limit) 

this seems work:

str_match(examples, "foo.*?(\\d+)")       [,1]          [,2] [1,] na            na   [2,] "foo 17"      "17" [3,] "foo 5"       "5"  [4,] "foo defg 11" "11" 

from ?regex:

by default repetition greedy, maximal possible number of repeats used. can changed ‘minimal’ appending ? quantifier.

from ?str_extract:

see also

?str_match extract matched groups; ?stri_extract underlying implementation.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -