15

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 ':' )

user1487000
  • 1,161
  • 3
  • 12
  • 17
  • 8
    The simplest way is to convert it into a datetime and catch the error when it fails. It is a datetime right? – Ben Feb 19 '13 at 20:22

3 Answers3

29

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

kofemann
  • 4,217
  • 1
  • 34
  • 39
  • 1
    Thing is, stuff like `'xxxxx/xxxxx/x 124453:24345'` also matches that. Use: `././.{4} .{2}:.{2}`, assuming it's any character. If it has to be digits: `\d/\d/\d{4} \d{2}:\d{2}` – TyrantWave Feb 19 '13 at 20:35
  • right, but the original post says: Assuming I want to check by if it has 2 /'s and a ':'. The example looks like a date format, but is it a date? – kofemann Feb 19 '13 at 20:36
  • He also gave a format he wanted to keep before, which looks exactly like a datetime format - I'd assume it was needed to be exact to that format personally. – TyrantWave Feb 19 '13 at 20:37
10

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

Ulas Keles
  • 1,681
  • 16
  • 20
8

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'
Octipi
  • 835
  • 7
  • 12