Precise Python time Regular Expression matching method analysis, python matching

Source: Internet
Author: User

Precise Python time Regular Expression matching method analysis, python matching

This example describes the exact Regular Expression matching method for Python time. We will share this with you for your reference. The details are as follows:

It is not easy to use regular expressions to accurately match the time.

Method 1:

>>> import re>>> t = '19:10:48'>>> m = re.match(r'(.*):(.*):(.*)', t)>>> m.groups()('19', '10', '48')

Method 2:

>>> t = '19:10:48'>>> m = re.match(r'(\d{2}):(\d{2}):(\d{2})', t)>>> m.groups()('19', '10', '48')

For example, the above is not accurate matching, for example, 24: 61: 61 obviously does not meet the requirements.

Hour (H), 0-23
Minute (M), 0-59
Seconds (S), 0-59
Precise matching of hours is as follows: 0? [0-9] | 1 [0-9] | 2 [0-3]
Accurate match in minutes: 0? [0-9] | [1-5] [0-9]
The exact match in seconds is as follows: 0? [0-9] | [1-5] [0-9]

The complete regular expression match is:

>>> t = '23:59:08'>>> p = re.compile(r'^(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9])$')>>> s = p.search(t)>>> s.groups()('23', '59', '08')

PS: here we will provide two very convenient Regular Expression tools for your reference:

JavaScript Regular Expression online testing tool:
Http://tools.jb51.net/regex/javascript

Regular Expression generation tool:
Http://tools.jb51.net/regex/create_reg

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.