Skip to content Skip to sidebar Skip to footer

Find 3 Letter Words

I have the following code in Python: import re string = 'what are you doing you i just said hello guys' regexValue = re.compile(r'(\s\w\w\w\s)') mo = regexValue.findall(string) My

Solution 1:

It's not regex, but you could do this:

words = [word for word in string.split() if len(word) == 3]

Solution 2:

You should use word boundary (\b\w{3}\b) if you strictly want to use regex otherwise, answer suggested by Morgan Thrapp is good enough for this.

Demo


Solution 3:

findall finds non-overlapping matches. An easy fix is to change the final \s to a lookahead; (?=\s) but you'll probably also want to extend the regex to cope with initial and final matches as well.

regexValue = re.compile(r'((?:^\s)\w\w\w(?: $|(?=\s))')

If this is not a regex exercise, splitting the string on whitespace is much mose straightforward.


Post a Comment for "Find 3 Letter Words"