user14987260
user14987260

Reputation:

If i am using re.finditer(), how can I limit the number of occurrences in python regex?

I am working on a python script that needs to go through a file and find certain paragraphs. I am able to successfully match the pattern using regex, however, the number of times that same paragraph occurs is more than 1. I simply need the first occurrence of the paragraph to be printed out.

Is there anything that I could add to my regular expression that would only return the first occurance.

This is my regex expression thus far... pattern = re.compile(//#|//\s#).+[\S\s] , then i did matches = pattern.finditer(file_name) , lastly i traversed through a for loop and printed print(i.group()). Note: the reason why i did finditer() instead of findall() is because i need it to be printed out as a string rather then a list.

Any guidance as to how I can tweak my current approach to only yield the first matched paragraph would be great!

Upvotes: 0

Views: 175

Answers (1)

Daweo
Daweo

Reputation: 36520

You might simply use .search rather than .finditer, example

import re
text = 'A1B2C3'
pattern = re.compile(r'([0-9])')
found = pattern.search(text).group()
print(found)  # 1
print(isinstance(found,str))  # True

Upvotes: 1

Related Questions