Python RE(总之,检查第一个字母区分大小写并且所有不区分大小写)

Fla*_*Hyd 2 python regex

在下面的例子中,我想匹配字符串"Singapore",其中"S"应该始终为大写,其余单词可以是低位或大写.但是在下面的字符串中,"s"是小写的,并且在搜索条件中匹配.任何机构都可以让我知道如何实现这个?

       import re       
            st = "Information in sinGapore "

            if re.search("S""(?i)(ingapore)" , st):
                print "matched"

Singapore => matched  
sIngapore => notmatched  
SinGapore => matched  
SINGAPORE => matched
Run Code Online (Sandbox Code Playgroud)

Ada*_*tan 5

评论说,丑陋的方式是:

>>> re.search("S[iI][Nn][Gg][Aa][Pp][Oo][Rr][Ee]" , "SingaPore")
<_sre.SRE_Match object at 0x10cea84a8>
>>> re.search("S[iI][Nn][Gg][Aa][Pp][Oo][Rr][Ee]" , "Information in sinGapore")
Run Code Online (Sandbox Code Playgroud)

更优雅的方式是匹配新加坡不区分大小写,然后检查第一个字母是S:

reg=re.compile("singapore", re.I)

>>> s="Information in sinGapore"
>>> reg.search(s) and reg.search(s).group()[0]=='S'
False

>>> s="Information in SinGapore"
>>> reg.search(s) and reg.search(s).group()[0]=='S'
True
Run Code Online (Sandbox Code Playgroud)

更新

根据您的评论 - 您可以使用:

reg.search(s).group().startswith("S")
Run Code Online (Sandbox Code Playgroud)

代替:

reg.search(s).group()[0]==("S")
Run Code Online (Sandbox Code Playgroud)

如果它看起来更可读.

  • 我认为`reg.search(s)和reg.search(s).group()[0] =='S'`条件是可读的. (2认同)