1

I've made this simple script for practicing RegEx that is supposed to read text that I copied to the clipboard and count how many times the word "corona" is mentioned. But i keep getting

"IndexError: string index out of range" which I get at matches.append(groups[0])

which I don't understand seeing as I'm starting the index at 0.

import re
import pyperclip

coronaRegEx = re.compile(r'Corona(virus)*', re.IGNORECASE)

text = str(pyperclip.paste())
matches = []
count = sum(matches)

for groups in coronaRegEx.findall(text):
    matches.append(groups[0])

if len(matches) > 0:
    pyperclip.copy(join(matches))
    print("Found " + count + " of instances")
else:
    print("No instances found")
4
  • 1
    Hint: The empty string has not content at index 0. Commented Mar 13, 2020 at 17:06
  • 1
    Can you point on which line you are getting the error? Commented Mar 13, 2020 at 17:08
  • 1
    I guess the error comes from matches.append(groups[0]), right? That's because you might get a result from findall that is an empty string which, of course, can't be used with [0]. Commented Mar 13, 2020 at 17:10
  • I don't follow. If the result from findall is an empty string shouldn't it print "No instances found"? But it should have content though I've typed the word "corona" and copied it... Commented Mar 13, 2020 at 17:30

1 Answer 1

2

I don't know your approach about the problem. I have simplified into following

import re
#import pyperclip
#I don't know what clipboard pasting you are doing so I have skipped pyperclip 
text = "Corona(virus) adsfj rl Corona adfs Corona adf Corona dfsd Corona Corona(virus) dfs asdf"
matches = []

for group in re.findall('Corona[virus]*',text):
    matches.append(group)

print(matches)

if len(matches) > 0:
    print("Found " + str(len(matches)) + " of instances")
else:
    print("No instances found")

see If this solves your problem. (this also handles empty string corner case)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.