Home > front end >  How to match regular expression characters in right position, wrong order?
How to match regular expression characters in right position, wrong order?

Time:01-13

Say my string is bucs. I would want to match buccaneers, tampa bay buccaneers, and bucs, but not "falcons".

I'm fairly new to regex, I tried:

re.findall("bucs", "buccaneers")

and it returned an empty list.

How would I go about doing this?

CodePudding user response:

You can separate your characters by .* to match strings in which they appear with no or some other characters between them:

In [1]: strs = "buccaneers", "tampa bay buccaneers", "bucs", "falcons"

In [2]: [s for s in strs if re.findall("b.*u.*c.*s", s)]
Out[2]: ['buccaneers', 'tampa bay buccaneers', 'bucs']
  • Related