I have a string and three patterns that I want to match and I use the python re
package. Specifically, if one of the pattern is found, output "Dislikes", otherwise, output "Likes". Brief info about the three patterns:
pattern 1: check if all character in string is uppercase letter
pattern 2: check if consecutive character are the same, for example,
AA
,BB
...pattern3 : check if pattern
XYXY
exist,X
andY
can be same and letters in this pattern do not need to be next to each other.
When I write the pattern separately, the program runs as expected. But when I combine the 3 patterns using alternation |
, the result is wrong. I have check the stackoverflow post, for example, here and here. Solution provided there do not work for me.
Here is the original code that works fine:
import sys
import re
if __name__ == "__main__":
pattern1 = re.compile(r"[^A-Z]+")
pattern2 = re.compile(r"([A-Z])\1")
pattern3 = re.compile(r"([A-Z])[A-Z]*([A-Z])[A-Z]*\1[A-Z]*\2")
word = sys.stdin.readline()
word = word.rstrip('\n')
if pattern1.search(word) or pattern2.search(word) or pattern3.search(word):
print("Dislikes")
else:
print("Likes")
If I combine the 3 pattern to one using the following code, something is wrong:
import sys
import re
if __name__ == "__main__":
pattern = r"([A-Z])[A-Z]*([A-Z])[A-Z]*\1[A-Z]*\2|([A-Z])\1|[^A-Z]+"
word = sys.stdin.readline()
word = word.rstrip('\n')
if re.search(word, pattern):
print("Dislikes")
else:
print("Likes")
If we call the 3 patterns p1
, p2
, and p3
, I also tried the following combination:
pattern = r"(p1|p2|p3)"
pattern = r"(p1)|(p2)|(p3)"
But they also do not work as expected. What is the correct to combine them?
Test cases:
- "Likes":
ABC
,ABCD
,A
,ABCBA
- "Dislikes":
ABBC
(pattern2),THETXH
(pattern3),ABACADA
(pattern3),AbCD
(pattern1)