-1

For this regular expression code, I tried to find the co-occurrence of two keywords, "refuse" or "decline" with "visit" or "service":

 row = " the patient declined to attend the visit"
    match1 = re.findall("(?=.*(refus\w*|declin\w*))(?=.*(servic\w*|visit\w*))", str(row))  # write it as social security
    print (match1)

When I print match1, it is the output:

[('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit'), ('declined', 'visit')]

But I want to print only one output: ('declined', 'visit')

would you please let me know what part of my code is wrong?

Red
  • 26,798
  • 7
  • 36
  • 58
Mary
  • 1,142
  • 1
  • 16
  • 37
  • Anchor the pattern at the start: `re.findall(r"^(?=.*(refus\w*|declin\w*))(?=.*(servic\w*|visit\w*))", str(row))` – Wiktor Stribiżew Jun 12 '20 at 14:01
  • @Wiktor, Thank you. So Why this error happens? – Mary Jun 12 '20 at 14:03
  • You are using `re.findall` that returns all matches from a string and you have a lot of them. Use `re.search` or anchor the pattern at the start. – Wiktor Stribiżew Jun 12 '20 at 14:03
  • But I have only one "declined" and one "visit" in the example. Finddall should find only those, is not it? – Mary Jun 12 '20 at 14:06
  • Have you tested your pattern? There are [13 matches](https://regex101.com/r/cdbAxw/1). Also, see ["Lookarounds (Usually) Want to be Anchored" at rexegg.com](https://www.rexegg.com/regex-lookarounds.html#anchor) – Wiktor Stribiżew Jun 12 '20 at 14:07

1 Answers1

1

re.findall() will return a list of all the occurrences of what is specified. If you only want, let's say, the first element of the list,

you can use a subscription of 0:

row = " the patient declined to attend the visit"
    match1 = re.findall("(?=.*(refus\w*|declin\w*))(?=.*(servic\w*|visit\w*))", str(row))  # write it as social security
    print (match1[0])
Red
  • 26,798
  • 7
  • 36
  • 58