moto
moto

Reputation: 940

Regex Match only if group contains another character

I'm trying to match time that contains a : and a . but can also be empty.

For example:

Match:
No Match: 5.564
Match: 1:23.321
Match: 12:02.213
No Match: 59.999

I have:

([0-9:\.]*)

But I'm not sure how to make sure that IF it does match, it also contains a :

Upvotes: 0

Views: 67

Answers (4)

Veera Balla Deva
Veera Balla Deva

Reputation: 788

dates = ['','5.564','1:23.321','12:02.213','59.999']
def check_date(dates):
    for date in dates:
        if (not date) or ('.' in date and ':' in date):
             yield date
list(check_date(dates))
>>>['', '1:23.321', '12:02.213']

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

import re
s = ['', '5.564', ' 1:23.321', ' 12:02.213', ' 59.999']
new_s = filter(lambda x:bool(re.findall('\.\w+:|:\w+\.|^$', x)), s)

Output:

['', ' 1:23.321', ' 12:02.213']

tests:

s = [['Match', ''], ['No Match', '5.564'], ['Match', ' 1:23.321'], ['Match', ' 12:02.213'], ['No Match', ' 59.999']]
for a, b in s:
   assert (a == 'Match')  == bool(re.findall('\.\w+:|:\w+\.|^$', b))
print('passed')

Output:

passed

Upvotes: 1

Stefan Collier
Stefan Collier

Reputation: 4682

Regexing can actually be slower than simple python in some occasions.

Here is a python function to check your matching (given you know it's a time):

def acceptable_time(test_value):
   return test_value == '' or \
               '.' in test_value and ':' in test_value

I'll performance test this against regex later.

Upvotes: 0

Kent
Kent

Reputation: 195289

This regex should work for you:

'^\d+:\d{2}\.\d{3}$|^$'

Upvotes: 1

Related Questions