简体   繁体   English

Python正则表达式:遍历键以查找完全匹配

[英]Python regex: Looping through keys to find exact match

I am trying to find the exact match of a certain string: 我试图找到某个字符串的完全匹配:

The user is prompted to enter a string, say 'AAAA' and I want to find the exact instants that this key is in a certain dictionary, dict that looks like {'AAAA':1, 'ZZZZ':2, 'BCBC':3} 提示用户输入一个字符串,说“ AAAA”,我想在某个字典中查找此键的确切时刻,字典看起来像{'AAAA':1,'ZZZZ':2,'BCBC' :3}

Right now i have: 现在我有:

string = input("enter string")
for key in dict.keys():
    regex = re.compile(r'^(key)$')
    if re.search(regex, string):
        match = re.search(string)
        print('match at %s') % (match.group(0))

I want the user to input a string, then to loop through all the possible keys and see if there's an exact match. 我希望用户输入一个字符串,然后遍历所有可能的键,看看是否存在完全匹配的内容。 If there is an exact match, I want to return the value (the index) where that key is. 如果存在完全匹配,我想返回该键所在的值(索引)。 Hence, if a user inputs AAAAZZZZ, I want it to print (1,2) 因此,如果用户输入AAAAZZZZ,我希望它打印(1,2)

I would not use regexp for this case but just look through the possible keys: 在这种情况下,我不会使用regexp,而只是浏览可能的键:

d = {'AAAA':1, 'ZZZZ':2, 'BCBC':3}

k = 'AAAAZZZZ'

result = []
start_index = 0
for index in range(0, len(k)+1):
    if k[start_index:index] in d:
        result.append(d[k[start_index:index]])
        start_index = index

print(result)

Sorry if my python is a bit rusty, but you should just store the indices you want and combine them after the loop. 抱歉,如果我的python有点生锈,但是您应该只存储所需的索引,并在循环后将其合并。

Note: this is probably not the most efficient way to go about this, but won't be terrible given a small dictionary. 注意:这可能不是解决此问题的最有效方法,但是对于一本小词典来说,这并不可怕。

string = input("enter string")
indices = []
for key in dict.keys():
    regex = re.compile(r'^(key)$')
    if re.search(regex, string):
        match = re.search(string)
        indices.append(dict[key])

print(','.join(map(str, indices)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM