python 正则表达式匹配大小写选项
python regex match case option
我想使用匹配案例选项。我有一段代码可以在列表中搜索字符串。我想有一种更优雅的方法可以做到这一点。
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]
resultList = []
matchCase = 0
for item in itemList:
if matchCase:
if re.findall(searchString, item):
resultList.append(item)
else:
if re.findall(searchString, item, re.IGNORECASE):
resultList.append(item)
我可以使用 re.findall(searchString, item, flags = 2)
,因为 re.IGNORECASE
基本上是一个整数 (2),但我不知道哪个数字表示 "matchcase" 选项。
您可以在推导式内强制执行不区分大小写的搜索:
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]
resultList =[]
matchCase = 1
if matchCase:
resultList = [x for x in itemList if x == searchString]
else:
resultList = [x for x in itemList if x.lower() == searchString.lower()]
print resultList
如果matchCase
为1
,则打印['maki']
,如果设置为0
,则打印['Maki', 'maki']
。
我想使用匹配案例选项。我有一段代码可以在列表中搜索字符串。我想有一种更优雅的方法可以做到这一点。
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]
resultList = []
matchCase = 0
for item in itemList:
if matchCase:
if re.findall(searchString, item):
resultList.append(item)
else:
if re.findall(searchString, item, re.IGNORECASE):
resultList.append(item)
我可以使用 re.findall(searchString, item, flags = 2)
,因为 re.IGNORECASE
基本上是一个整数 (2),但我不知道哪个数字表示 "matchcase" 选项。
您可以在推导式内强制执行不区分大小写的搜索:
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]
resultList =[]
matchCase = 1
if matchCase:
resultList = [x for x in itemList if x == searchString]
else:
resultList = [x for x in itemList if x.lower() == searchString.lower()]
print resultList
如果matchCase
为1
,则打印['maki']
,如果设置为0
,则打印['Maki', 'maki']
。