'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.
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
This way will work:
(r"a+.+a", text.lower())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul |
| Solution 2 | |
| Solution 3 | Gustavo Amaya |
| Solution 4 | Andrew |
