find words of length 4 using regular expression

后端 未结 2 642
轮回少年
轮回少年 2021-01-20 02:20

I am trying to find words in regular expression with length 4

I am trying this but I am getting an empty list:

#words that have length of 4
s = inpu         


        
相关标签:
2条回答
  • 2021-01-20 02:54

    Use word boundaries \b. When you add anchors in your regex like ^[a-zA-Z]{4}$, this would match the lines which have only four alphabets. It won't check for each individual words. ^ asserts that we are at the start and $ asserts that we are at the end. \b matches between a word character and a non-word character(vice versa). So it matches the start (zero width) of a word or end (zero width) of a word.

    >>> s = "here we are having fun these days"
    >>> re.findall(r'\b[a-zA-Z]{4}\b', s)
    ['here', 'days']
    
    0 讨论(0)
  • 2021-01-20 03:03

    No need for a (possibly) complicated regex, you can just use a list comprehension:

    >>> s = "here we are having fun these days"
    >>> [word for word in s.split() if len(word) == 4 and word.isalpha()]
    ['here', 'days']
    >>> 
    
    0 讨论(0)
提交回复
热议问题