Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mike Brooks
3,389 PointsPython: Using variables in regular expression meta-characters{}
In one of the regular expression checks I was trying to do the following:
def find_words(count, myString):
print(myString)
return re.findall("\w{count,}", myString)
to find words with a count or more number of letters in myString
It came back with an empty list. I googled trying to put variables in metacharacters but all the examples were numeric.
I got it to work using the following:
def find_words(count, myString):
print(myString)
return re.findall(("\\w{" + str(count) + ",}"), myString)
BUT I am assuming there is a much more elegant way to do this.
Any help appreciated.
1 Answer
Stuart Wright
41,120 PointsI'm not an expert at regex, and I wouldn't necessarily say this is more elegant than your solution, but it's at least an alternative:
def find_words(count, myString):
print(myString)
return re.findall(r"\w{{{},}}".format(count), myString)
It uses string formatting rather than the concatenation technique you used.
Note that the double braces which form the {m, n} part of the string have their curly braces doubled. This is necessary to distinguish them from the {} placeholder required for the string formatting.