1

我想从文本中进行区分大小写的匹配。在以下情况下,我尝试使用 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

4 回答 4

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
于 2013-02-26T16:56:29.060 回答
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
于 2013-02-26T18:47:21.047 回答
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 -
于 2013-03-04T18:15:35.987 回答
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
于 2013-02-26T17:00:30.383 回答