9 Practical Examples of Using Regular Expressions in Python
There are some ugly regexes in that. Matching minutes as 0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9] when you could just write [0-5]\d or [0-5][0-9] is why people think regexes are unreadable.
Python regular expressions, REGEX
Python match a string with regex - Stack Overflow
how hard is it to learn regex... is it worth learning?
Hello my friend! I am learning python using the popular book, Automate the boring stuff book and I came accross the regeneration class. I tried non-greedy matching the two groups of characters in a string. The group method returned the first group but didnt the second group. I asked chat gpt and it said my code is fine. It gave me some probable causes pf such an issue that there us a newline but that isn't so. Attached is my code.
Will appreciate your assistance and comments. Thank you
-
name_regex1 = re.compile(r"First Name: (.?) Last Name: (.?)")
-
-
name2 = name_regex1.search("First Name: Gideon Last Name: Asiak")
-
-
print(name2.group(2))
Sorry I couldn't attach the screenshot, but this is the code up here.(please know that there are no newline, each statement is in its line)
NOTE: there is an asterisk between the '.' and '?'. I dont know why when I post it dissapears.
Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:
>>> line = 'This,is,a,sample,string'
>>> "sample" in line
True
The r makes the string a raw string, which doesn't process escape characters (however, since there are none in the string, it is actually not needed here).
Also, re.match matches from the beginning of the string. In other words, it looks for an exact match between the string and the pattern. To match stuff that could be anywhere in the string, use re.search. See a demonstration below:
>>> import re
>>> line = 'This,is,a,sample,string'
>>> re.match("sample", line)
>>> re.search("sample", line)
<_sre.SRE_Match object at 0x021D32C0>
>>>