user1870840
user1870840

Reputation: 81

How to check if text has certain format?

How to check if text/string has (number:number-number) format in Python?

An example is (7:10-9)

I think I need to use Regex?

Upvotes: 3

Views: 793

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Yes, that would be the easiest. Example:

In [1]: import re

In [2]: re.match('\(\d+:\d+-\d+\)', '(7:10-9)')
Out[2]: <_sre.SRE_Match at 0x24655e0>

In [3]: re.match('\(\d+:\d+-\d+\)', '(7)')

In [4]: 

As a function:

def match(s):
    return bool(re.match('\(\d+:\d+-\d+\)', s))

Don't forget to look through the docs.

Upvotes: 5

Related Questions