a fair player
a fair player

Reputation: 11776

Python, regex dynamic count

So far I have this code:

def find_words(m_count, m_string):
    m_list = re.findall(r'\w{6,}', m_string)
    return m_list

is there a way to use m_count instead of using the count number (6) explicitly??

Upvotes: 1

Views: 147

Answers (3)

Octavio Soto
Octavio Soto

Reputation: 791

Convert the int to string and added to you reg exp like this:

def find_words(m_count, m_string):
    m_list = re.findall(r'\w{'+str(m_count)+',}', m_string)
    return m_list

Upvotes: 2

ospahiu
ospahiu

Reputation: 3525

You can use format(), and escape the curly braces.

>>> import re
>>> m_count = 6
>>> print re.findall(r'\w{{{},}}'.format(m_count),'123456789 foobar hello_world')
['123456789', 'hello_world']

Full method body:

def find_words(m_count, m_string):
    m_list = re.findall(r'\w{{{},}}'.format(m_count), m_string)
    return m_list

Upvotes: 0

anubhava
anubhava

Reputation: 785176

You can build a regex by concatenating your count variable and static part like this:

>>> m_count = 6
>>> re.findall(r'\w{' + str(m_count) + ',}', 'abcdefg 1234 124xyz')
['abcdefg', '124xyz']

Upvotes: 1

Related Questions