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 goal is to find any 3-letter word, but for some reason, I seem to get only "eat" and not "you" on my list. I realized that this could be because the space between the two overlaps, and since the space is already in use, it cannot be part of "you." So, how do I find only three words from a string like this?

+4
source share
3 answers

This is not a regular expression, but you can do this:

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

(\b\w{3}\b), , , Morgan Thrapp, .

+6

findallfinds matching matches. An easy fix is ​​to change the final \sto lookahead; (?=\s), but you probably also want to expand the regex to deal with the initial and final matches.

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

If this is not a regular expression exercise, splitting a string into spaces is very simple.

+1
source

All Articles