stringr, str_extract: how to do positive lookbehind?

Viewed 5444

Very simple problem. I just need to capture some strings using a regex positive lookbehind, but I don't see a way to do it.

Here's an example, suppose I have some strings:

library(stringr)
myStrings <- c("MFG: acme", "something else", "MFG: initech")

I want to extract the words which are prefixed with "MFG:"

> result_1  <- str_extract(myStrings,"MFG\\s*:\\s*\\w+")
>
> result_1
[1] "MFG: acme"    NA             "MFG: initech"

That almost does it, but I don't want to include the "MFG:" part, so that's what a "positive lookbehind" is for:

> result_2  <- str_extract(myStrings,"(?<=MFG\\s*:\\s*)\\w+")
Error in stri_extract_first_regex(string, pattern, opts_regex = attr(pattern,  : 
  Look-Behind pattern matches must have a bounded maximum length. (U_REGEX_LOOK_BEHIND_LIMIT)
> 

It is complaining about needing a "bounded maximum length", but I don't see where to specify that. How do I make positive-lookbehind work? Where, exactly, can I specify this "bounded maximum length"?

3 Answers

I wrote the code in python using lookbehind. if the parser find MFG: then it will grab the next word

txt="MFG: acme, something else, MFG: initech"
pattern=r"(?<=MFG\:)\s+\w+"
matches=re.findall(pattern,txt)
for match in matches:
   print(match)

output:

 acme
 initech
Related