Python RE(总之检查第一个字母是否区分大小写,其余部分不区分大小写)

2024-05-14

在下面的情况下,我想匹配字符串“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

正如所评论的,丑陋的方式是:

>>> 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")

更优雅的方法是匹配 Singapore 不区分大小写,然后检查第一个字母是否是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

Update

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

reg.search(s).group().startswith("S")

代替:

reg.search(s).group()[0]==("S")

如果它看起来更具可读性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python RE(总之检查第一个字母是否区分大小写,其余部分不区分大小写) 的相关文章

随机推荐