Python regular expression to determine whether a string is in all lower case

Source: Internet
Author: User
Python regular expression to determine whether all strings are in lowercase. For more information, see The code is as follows:


#-*-Coding: cp936 -*-
Import re
S1 = 'adkdk'
S2 = 'abc123efg'

An = re. search ('^ [a-z] + $', s1)
If:
Print 'S1: ', an. group (), 'all lowercase'
Else:
Print s1, "all lowercase! "

An = re. match ('[a-z] + $', s2)
If:
Print 's2: ', an. group (), 'all lowercase'
Else:
Print s2, "not all lowercase! "



1. Regular expressions are not part of python. when using them, you need to reference the re Module.

2. the matching format is re. search (regular expression with matching string) or re. match (regular expression with matching string ). The difference between the two is that the latter starts with the start character (^) by default. Therefore,

Re. search ('^ [a-z] + $', s1) is equivalent to re. match ('[a-z] + $', s2)
3. if the match fails, an = re. search ('^ [a-z] + $', s1) returns None.

Group is used to group matching results.

The code is as follows:


Import re
A = "123abc456"
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (0) #123abc456, returns the whole
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (1) #123
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (2) # abc
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (3) #456

1) in the regular expression, the matching results are divided into three groups by three sets of parentheses.

Group () and group (0) are the results of matching the regular expression.

Group (1) lists the matching parts of the first bracket, group (2) lists the matching parts of the second bracket, and group (3) lists the matching parts of the third bracket.

2) if no matching is successful, re. search () returns None

3) of course, Zheng's expression does not contain parentheses, and group (1) is definitely incorrect.

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.