1

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??

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

If you notice I had same answer posted 5-6 minutes ago :)
1

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']

1 Comment

For those who might be using PyCharm, if you face "pattern expected" error, you can define the pattern on a different line (pattern = r'\w{' + str(m_count) + ',}') and then use the pattern directly (re.findall(pattern, 'abcdefg 1234 124xyz'))
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.