Reputation: 95
I need to be able to detect patterns in a string in Python. For example:
xx/xx/xx (where x is an integer).
How could I do this?
Upvotes: 0
Views: 4749
Reputation:
This is a case for regular expressions. The best resource to start out that I have read so far would be from a book called "Automate The boring Stuff with Python.
This is just a sample of how you migth implement regular expressions to solve your problem.
import re
regex = re.compile(r'\d\d\/\d\d/\d\d$')
mo = regex.findall("This is a test01/02/20")
print(mo)
and here is the output
['01/02/20']
Imports python's library to deal with regex(es) import re
Then you ceate a regex object with:
regex = re.compile(r'\d\d\/\d\d/\d\d')
This migth look scary but it's actually very straight forward. Youre defining a pattern. In this case the pattern is \d\d or two digits, followed by / then two more and so on.
Here is a good link to learn more
https://docs.python.org/2/library/re.html
Thou I defenetly suggest picking up the book.
Upvotes: 0
Reputation: 121
Assuming you want to match more than just dates, you'll want to look into using Regular Expressions (also called Regex). Here is the link for the re Python doc: https://docs.python.org/2/library/re.html This will tell you all of the special character sequences that you can use to build your regex matcher. If you're new to regex matching, then I suggest taking a look at some tutorials, for example: http://www.tutorialspoint.com/python/python_reg_expressions.htm
Upvotes: 1