0

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?

1
  • Looks like you want to detect dates. There are plenty of questions that cover that already. Commented Jul 3, 2016 at 23:43

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.