11
votes

I have a bunch of strings but I only want to keep the ones with this format:

x/x/xxxx xx:xx

What is the easiest way to check if a string meets this format? (Assuming I want to check by if it has 2 /'s and a ':' )

3
The simplest way is to convert it into a datetime and catch the error when it fails. It is a datetime right? - Ben

3 Answers

24
votes

try with regular expresion:

import re
r = re.compile('.*/.*/.*:.*')
if r.match('x/x/xxxx xx:xx') is not None:
   print 'matches'

you can tweak the expression to match your needs

9
votes

Use time.strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError.

8
votes

If you use regular expressions with match you must also account for the end being too long. Without testing the length in this code it is possible to slip any non-newline character at the end. Here is code modified from other answers.

import re
r = re.compile('././.{4} .{2}:.{2}')
s = 'x/x/xxxx xx:xx'
if len(s) == 14:
  if r.match(s):
    print 'matches'