1

テキストから大文字と小文字を区別して一致させたい。以下のケースでは、re.search を使用して "Ca.iNy" を照合しようとしました。"C" を大文字にする必要がある場所を照合し、残りのすべての文字がいずれかのケースになるようにします。大文字と小文字が一致する場合、変数に値を設定します。

SOのヘルプフォームを取得し、最初の文字が大文字かどうかをチェックして実装しましたが、1回のチェックで問題なく機能しました。

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
[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 に答える
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
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 に答える