破解隐藏在字符中的密码(Python)

2018-01-15  本文已影响325人  52_St

一个密码藏在在一个字符串中,密码的埋藏地点符合以下规律:

首先,考虑的是很简单的正则表达式:

import re

S = '密码字符串'
rs = re.findall(r'[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]',S)
print(''.join(rs))

但是上述方法有缺陷,在这里给出一个不满足条件的例子:
test = 'AACcqDEDiEEEpEEqEEElEEEoFDFvLLDsKbLDKeOOO'
正确的密码应该为:ilove
但上述代码的运行结果为:il

为了解决上述问题,重新整理思路,最终的代码如下,已经添加了注释,这里就不详细解释了。

import re

test = 'AACcDEDiEEEpEEqEEElEEEoFDFvLLDsKbLDKeOOO'
# test = 'cAACVcccccccCDDeCCCfCC'
code = ''
while test:
    # 确定字符串中是否有小写字母
    if not test.isupper():
        # 获取原始字符串第一个小写字母
        first_low_character = re.findall('[a-z]', test)[0]
        # 获取第一个小写字母的索引
        first_low_index = test.index(first_low_character)
        # 判断第一个小写字母前面是否恰好有 3 个大写字母
        if first_low_index == 3:
            # 将 AAAb 删除 更新字符串
            test = test[first_low_index + 1:]
            # 检查更新后的字符串是否为空 并确定是否有小写字母
            if test and not test.isupper():
                # 获取更新后的字符串第一个小写字母
                two_low_character = re.findall('[a-z]', test)[0]
                # 获取更新后的字符串第一个小写字母的索引
                two_low_index = test.index(two_low_character)
                # 判断更新后的字符串第一个小写字母 前面 是否恰好有 3 个大写字母
                # 也就是
                # 判断原始字符串第一个小写字母 后面 是否恰好有 3 个大写字母
                # 上面这两句话 意义相同
                if two_low_index == 3:
                    # 存储满足条件的小写字母
                    code += first_low_character
                else:
                    # 更新字符串
                    test = test[two_low_index + 1:]
            else:
                # # 判断更新后的字符串恰好有 3 个大写字母
                if len(test) == 3:
                    # 存储满足条件的小写字母
                    code += first_low_character
        else:
            # 更新字符串
            test = test[first_low_index + 1:]
    else:
        # 字符串中已经没有小写字母 直接退出循环
        break

print(code)

if code == 'cilove':
    print('测试成功!')
else:
    print('测试失败!')

360截图16620615114117128.jpg
上一篇下一篇

猜你喜欢

热点阅读