Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find 3 letter words

Tags:

python

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 only be getting the "are" and not the "you" in my list. I figured this might be because the space between the two overlap, and since the space is already used it cannot be a part of "you". So, how should I find only three letter words from a string like this?

like image 250
Linus Johansson Avatar asked Dec 06 '22 17:12

Linus Johansson


2 Answers

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

words = [word for word in string.split() if len(word) == 3]
like image 198
Morgan Thrapp Avatar answered Dec 15 '22 01:12

Morgan Thrapp


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

like image 35
dnit13 Avatar answered Dec 15 '22 03:12

dnit13