How to match regular expression characters in right position, wrong order?

Question:

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?

Asked By: earningjoker430

||

Answers:

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']
Answered By: Nic Wolff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.