0

Can someone explain character classes; why answer is Match 1 and Match 2 and not Match 3

import re pattern = r"[^A-Z]" if re.search(pattern, "this is all quiet"): print("Match 1") if re.search(pattern, "AbCdEfG123"): print("Match 2") if re.search(pattern, "THISISALLSHOUTING"): print("Match 3") Result: >>> Match 1 Match 2 >>> The pattern [^A-Z] excludes uppercase strings. Note, that the ^ should be inside the brackets to invert the character class. ........can someone explain why answer is Match 1 and Match 2 and not Match 3

19th Aug 2020, 5:32 AM
Hiral Jain
Hiral Jain - avatar
4 Respostas
+ 3
you ask for not all in A-Z in your pattern.
19th Aug 2020, 6:02 AM
Oma Falk
Oma Falk - avatar
+ 1
Please note,what is being inverted is the pattern and not the string being matched.You can look at [^A-Z] as [a-z] rather. Hope am right coz am still taking in the Regex concepts🤔😆😆
19th Mar 2021, 12:28 PM
Henry Mwandama
Henry Mwandama - avatar
0
because of 2 things firstly this is search not match in the code "if re.search.... so it accept any part of the code unlike match that accepts only the beginning of the code secondly the ^ in r"[^A-Z] where it says to search for not A to Z (upper case) so if the text contains only upper case it is not accepted, but if the search function found any other character than upper case it will be a match
4th Jan 2023, 9:32 PM
Ali M
Ali M - avatar
0
Charater class patterns that start with a ‘^’ means everything that is NOT in your character class pattern. So if you exclude all the ‘A-Z’ characters from the string you are searching on you still have other charters ‘a-z’ and digits ‘0-9’ that would remain iin the search. To help undestand this another way You could think of as follows: - pattern = r“[^A-Z]” Is the same as pattern = r”[a-z0-9]” So what you will see is the strings for Match 1 and Match 2 do have some characters that match. Where as the string for Match 3 does NOT have any charters that match. Hope this helps to answer your question and to support the other explainations Happy coding
22nd Mar 2023, 10:41 AM
Abid Mumtaz