0

I have a python code like

            for i in re.finditer('something(.+?)"', html):

I am now trying to find out how many times its going to loop before going to that loop..in other words the length of array i. Could anyone give me an alternative but similar code with with I get length of the loop.

2
  • 2
    Could you elaborate why you need to know the length beforehand? Commented Apr 23, 2013 at 9:03
  • I'd like to show a progress of the activity with percentage.. Commented Apr 23, 2013 at 10:31

3 Answers 3

3
x = list(re.finditer('something(.+?)"', html))

if len(x)
     ....

for i in x:
     ....

findall is not an adequate replacement since it returns strings, not match objects.

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

Comments

1

You can't do that with re.finditer because it returns an iterator which doesn't know when it's finished until it does (since it finds the next match on each iteration) ..., you'll have to use re.findall.

matches = re.findall('something(.+?)"', html)
num_loops = len(matches)

or use @thg435's approach if you do in fact need the match objects.

2 Comments

How do I implement re.findall as well as get the index number?
@Abul Hasnat you just use len(..) on the list. If you want the index number for each match then do for i, m in enumerate(re.findall(...))
1

finditer returns the results as it finds them. There is no way finditer can tell you how many times you will loop in advance.

You need to use something else. Either re.findall or possibly re.search to get the length

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.