使用python re.search进行区分大小写的匹配

时间:2013-02-26 16:35:08

标签: python regex

我想从文本中进行区分大小写的匹配。在下面的例子中,我尝试使用re.search匹配“Ca.iNy”,我想匹配“C”应该是大写字母并且所有字符可能在任何情况下休息。如果它与我想要的情况匹配,则为变量设置一个值。

我已经采取了SO的帮助表格并通过检查第一个字母是否为大写来实现,并且它可以用于单次检查。

s = "The details belong to (Ca.iNy.) in this case"
reg = re.compile("Ca.iny.", re.I)
reg.search(s).group().startswith("C").

但是,我无法在“if else循环”中使用它。我尝试了下面的代码,但搜索似乎不区分大小写。有人可以请我吗?

import re

st = "The details belong to (Ca.iNy.) in this case"
Mval = ''

if re.search(r"C(?i)a.iny", st):
    Mval = "AAAAA"
elif re.search(r"(?i)Ky.", st):
    Mval = "BBBBB"
elif re.search(r"(?i)M.sa.", st):
    Mval = "CCCCC"
else:
    Mval = "DDDDD"

print Mval

4 个答案:

答案 0 :(得分:0)

import re

st = "The details belong to (Ca.iNy.) in this case"
Mval = ''

if re.search(r"C""(?i)a.iny", st):
    Mval = "AAAAA"
elif re.search(r"(?i)Ky.", st):
    Mval = "BBBBB"
elif re.search(r"(?i)M.sa.", st):
    Mval = "CCCCC"
else:
    Mval = "DDDDD"

print Mval

答案 1 :(得分:0)

import re

st = "The details belong to (Ca.iNy.) in this case"
Mval = ''

if re.search(r"C[a-z].[a-z][a-z]", st):   # Only change
    Mval = "AAAAA"
elif re.search(r"(?i)Ky.", st):
    Mval = "BBBBB"
elif re.search(r"(?i)M.sa.", st):
    Mval = "CCCCC"
else:
    Mval = "DDDDD"

print Mval

答案 2 :(得分:0)

import re
All = {"CA.ing": 3, "cA.aec": 10}
st = "The details belong to (Ca.inY.) in this case"
Mval = ''
class1 = r"[a-z][a-z].[a-z][a-z][a-z]"
class2 = r"[a-z][a-z][a-z][a-z][a-z][a-z]"  # For strings like alaska

if re.search(class1, st, flags=re.IGNORECASE):
    found_value = re.search(class1, flags=re.IGNORECASE).group()
    if found_value in All.keys():
        Mval = All[found_value]
elif re.search(class2, st):
    found_value = re.search(class2, st).group()
    if found_value in All.keys():
        Mval = All[found_value]

#This will return a KeyError if a string is present not in your dictionary
#Note : You can take care of the different case sensitive cases in the dictionary, by
# only including the proper cases

答案 3 :(得分:0)

[mport re

reg = re.compile('([a-z]{2})\.[a-z]{3}',re.I)

def code(X,r):
    for ma in r.finditer(X):
        if ma.group(1)[0].upper()==ma.group(1)[0]:
            GV = 'OK'
        else:
            GV = '- bad match -'
        yield '  {!s:10}  {!s:^13}'.format(ma.group(), GV)

data = ('Ca.imo  Ca.IMo gggg Ca.iMo   CL.icv   cl.icv  cL.icv'
        'hhhh  ca.ghc  Rl.axp  bbb  Rl.AXp  nm.fgt')

print '\n'.join(res for res in code(data,reg))

结果

  Ca.imo           OK      
  Ca.IMo           OK      
  Ca.iMo           OK      
  CL.icv           OK      
  cl.icv      - bad match -
  cL.icv      - bad match -
  ca.ghc      - bad match -
  Rl.axp           OK      
  Rl.AXp           OK      
  nm.fgt      - bad match -