Python中,正则表达式动态计
问题描述:
到目前为止,我有这样的代码:Python中,正则表达式动态计
def find_words(m_count, m_string):
m_list = re.findall(r'\w{6,}', m_string)
return m_list
有使用m_count
,而不是使用计数次数(6)明确的方式?
答
您可以通过连接您的计数变量和静态部分像这样建立一个正则表达式:
>>> m_count = 6
>>> re.findall(r'\w{' + str(m_count) + ',}', 'abcdefg 1234 124xyz')
['abcdefg', '124xyz']
答
转换整型到字符串,并添加到您章实验值是这样的:
def find_words(m_count, m_string):
m_list = re.findall(r'\w{'+str(m_count)+',}', m_string)
return m_list
+0
如果您发现我有[相同的答案发布5-6分钟前](http://*.com/a/39043542/548225):) – anubhava
对于那些谁可能会使用PyCharm,如果你(pattern = r'\ w {'+ str(m_count)+',}'),然后直接使用该模式(re.findall(pattern,'' abcdefg 1234 124xyz')) –