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

2 投票
4 回答
6258 浏览
提问于 2025-04-17 17:12

我想从文本中进行区分大小写的匹配。在下面的例子中,我尝试用 re.search 来匹配 "Ca.iNy",我希望 "C" 必须是大写的,而其他字符可以是任意大小写。如果匹配成功,我想把一个值设置给一个变量。

我参考了 Stack Overflow 的内容,检查第一个字母是否是大写,这个方法在单次检查时效果很好。

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
[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 -
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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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

撰写回答