Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find words in a string with the same prefix through RegEx in Python

Tags:

python

regex

Given a string...

truth = "I like turtles, turtles4756-+=[]}{@##:) I like"

how could you get the array of words beginning with a known prefix?

e.g. 'turt'

["turtles", "turtles4756-+=[]}{@##:)"]

like image 738
James Avatar asked Nov 22 '25 11:11

James


1 Answers

In [1]: import re

In [2]: truth = "I like turtles, turtles4756-+=[]}{@##:) I like"

In [3]: re.findall?
    Definition: re.findall(pattern, string, flags=0)
    ...
    Return a list of all non-overlapping matches in the string.

    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

# [word boundary]turt followed by word characters
In [4]: re.findall(r'\bturt\w*', truth)
Out[4]: ['turtles', 'turtles4756']

# [word boundary]turt followed by non-whitespace characters
In [5]: re.findall(r'\bturt\S*', truth)
Out[5]: ['turtles,', 'turtles4756-+=[]}{@##:)']

In [10]: truth = "I like turtles, turtles4756-+=[]}{@##:) I like superturtles"

In [11]: re.findall(r'turt\S+', truth)
Out[11]: ['turtles,', 'turtles4756-+=[]}{@##:)', 'turtles']

In [12]: re.findall(r'\bturt\S+', truth)
Out[12]: ['turtles,', 'turtles4756-+=[]}{@##:)']
like image 86
Pavel Anossov Avatar answered Nov 24 '25 23:11

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!