flamingo_stark
flamingo_stark

Reputation: 151

Regex - Checks a letter repeating at least twice

I want to check whether a string includes the letter a (lowercase or uppercase) at least twice. I wrote the regex pattern and checked its working on regex101.com.

[aA]+[^aA]*[aA]+

Sample strings to match:

banana   #True
pineapple  #False
Animal Kingdom  #True
A is for apple  #True

Though the code is working as expected, I am concerned about whether there are better ways to get it done, or are there some cases that aren't going to match with my regex.

Upvotes: 1

Views: 5783

Answers (6)

Eszti
Eszti

Reputation: 1

re.search(r"[aA].*a", text)

Upvotes: 0

Gustavo Amaya
Gustavo Amaya

Reputation: 1

i wrote this and it worked:

re.search(r"a[a-z ]*a", text, re.IGNORECASE)

so find the first a, go through any of these characters plus the " ", any number of times until you find another a, and this regardless of the case.

Upvotes: 0

Andrew
Andrew

Reputation: 1

This way will work:

(r"a+.+a", text.lower())

Upvotes: -2

SSV 1
SSV 1

Reputation: 33

Try this one very simple:

    (r"a.*a", text, re.IGNORECASE)

Another way is:

if you put [Aa]{n} it means you want A/a to be repeated for a consecutively n times which is not in this case as a is separated by characters for example in banana, a is separated by n... so we use [Aa].*[Aa]

    (r"[Aa].*[Aa]", text)

Both ways it works.

Upvotes: 0

cdlane
cdlane

Reputation: 41872

Why not go simple:

[aA].*[aA]

Additional pattern syntax like [^aA]* doesn't seem to add anything.

Upvotes: 8

Paul
Paul

Reputation: 2076

pineapple shouldn't match, should it?

I would suggest ([aA].*){2,} because I think it's easier to read.

Here with unit tests based on your suggestions: https://regex101.com/r/WJnTW5/2

Upvotes: 1

Related Questions