0

Suppose I have String

myString = "Keyword abckeyword abc blah"

I want to capture occurence of both keyword and value immediately following keyword until white space

myregex = re.compile(fr"({keyword})\s*(\S+)", re.MULTILINE | re.IGNORECASE)

for m in myregex.finditer(myString):
   print(m)

I get result as keyword abckeyword, but second match is not captured. How do I fix this ?

<_sre.SRE_Match Object; span=(0,17), match='keyword abckeyword'>

Expected result :

<_sre.SRE_Match Object; span=(0,17), match='keyword abckeyword'>
<_sre.SRE_Match Object; span=(11,21), match='keyword abc'>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • `re.findall(rf"(?=(({keyword})\s+(\S+)))", s)` should do it. – ggorlen Apr 11 '20 at 20:58
  • Here, just wrap the pattern with a capturing group and place inside a positive lookahead. Note you need a word boundary before the keyword, `rf"(?=\b({keyword}\s+\S+))"` – Wiktor Stribiżew Apr 11 '20 at 20:59
  • Your desired "second match", ,`'keyword abc'` does not satisfy your requirement, "I want to capture occurrence of both keyword and value immediately following keyword until white space". – Cary Swoveland Apr 11 '20 at 21:09

0 Answers0