Home > Blockchain >  Python Regex Find all words starting with [duplicate]
Python Regex Find all words starting with [duplicate]

Time:10-04

I am trying to find all the words starting with "a" in a given string with Regex. But it doesn't search word by word.

Can anyone provide any solution?

import re

pattern = re.compile(r'^a. ')
result = pattern.findall("I have an apple and a pen. ")
print(result)

Output: []

CodePudding user response:

You can use word boundaries:

pattern = re.compile(r"\ba.*?\b")
pattern.findall("I have an apple and a pen. ")
# ['an', 'apple', 'and', 'a']
  • Related