[英]How to check if string contains exact match of string?
我正在尝试检查是否可以在字符串中找到我的 dict 键。 问题是我的代码不匹配整个字符串,而是遍历每个字符。
我试过这样:
val_dict= {'1/2 pint': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text:
print(x, val_dict.get(x))
但我得到
1/2 pint half
1 one
而不是只有“一半”。 如何解决? 据我所知,'/' 不是转义字符。
编辑:鉴于其他主题中提供的解决方案,我尝试了正则表达式:
for x in val_dict:
if re.search(rf"\b{x}\b", text, re.IGNORECASE):
print(x + " match")
>>> 1/2 pint match
>>> 1 match
没关系,因为\\b
但是:
for x in val_dict:
if re.search(rf"^{x}$", text, re.IGNORECASE):
print(x + " match")
应该匹配确切的出现,但没有给出结果。 为什么?
请注意,我的 dict 键可能包含空格,因此无法按空格拆分文本。
这是修复:
val_dict= {'1/2': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text.split(' '):
print(x, val_dict.get(x))
输出
1/2 half
您可以尝试使用正则表达式
import re
val_dict= {r'1/2': 'half', r'1[!/]': 'one', '5': 'five'}
# ^"1/2"^ ^ 1 with NO SLASH
text = 'I need 1/2 pint of beer'
for x in val_dict:
if re.match(x, text):
print(x, val_dict.get(x))
预期输出:
1/2 half
您可以定制 RegEx 以更好地满足您的需求!
我正在尝试检查是否可以在字符串中找到我的字典键。 关键是我的代码本身并不匹配整个字符串,而是遍历每个字符。
我试过像这样:
val_dict= {'1/2 pint': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text:
print(x, val_dict.get(x))
但是我越来越
1/2 pint half
1 one
而不只是“一半”。 怎么解决呢? 据我所知,“ /”不是转义字符。
编辑:鉴于其他主题中提供的解决方案,我尝试了正则表达式:
for x in val_dict:
if re.search(rf"\b{x}\b", text, re.IGNORECASE):
print(x + " match")
>>> 1/2 pint match
>>> 1 match
没关系,因为\\b
但是:
for x in val_dict:
if re.search(rf"^{x}$", text, re.IGNORECASE):
print(x + " match")
应该匹配确切的出现,但不给出结果。 为什么?
请注意,我的字典键可能包含空格,因此按空格分隔文本将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.