1

我有一个在 Python 中似乎无法解决的问题。我有一个模式需要匹配字符数组中的任何字符。如果没有,那就有问题了。所以这里是我的例子:

pattern = "0000 006e 0022 0002 0156 00ac 0016 0016 0016 0041 0016 0041 0016 0041 0016 0016 0016 0041 0016 0041 0016 0041 0016 0041 0016 0041 0016 0041 0016 0016 0016 0016 0016 0016 0016 0016 0016 0041 0016 0016 0016 0016 0016 0041 0016 0016 0016 " 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0041 0016 0041 0016 0041 0016 0016 0016 0016 0016 0016 0016 0041 06016 05 0010 06016 05010 06

allowedCharacters = "123456789abcdef"

所以我的目标是查看模式是否符合允许的字符。在 C# 中,我执行了以下操作,但我不知道如何在 Python 中完成此操作。

这是我当前的代码。

        # Test that there are only valid characters in the pattern.
        charPattern = list(pattern)
        expression = list("01234567890abcdef")

        for currentChar in pattern:
            if len(charPattern) - pattern[-1::-1].index("0123456789abcdef") - 1:
                self.assertTrue(False, logger.failed("The invalid character: " + currentChar + " was found in the IRCode pattern for: " + ircode))`enter code here`

欢迎任何想法/建议/代码示例。

谢谢。

4

2 回答 2

3

试试这个代码:

import re
p = re.compile(r'^[0123456789abcdef\s]+$')
str = "0000 006e 0022 0002 0156 00ac 0016 0016 0016 0041 0016 0041 0016 0041 0016 0016 0016 0041 0016 0041 0016 0041 0016 0041 0016 0041 0016 0041 0016 0016 0016 0016 0016 0016 0016 0016 0016 0041 0016 0016 0016 0016 0016 0041 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0041 0016 0041 0016 0041 0016 0016 0016 0016 0016 0016 0016 0041 0016 05e0 0156 0055 0016 0e41"

if(p.match(str)):
  print("passed")
else:
  list = re.findall('([^0123456789abcdef\s])+', str)
  print(list)

它将在字符串中搜索0123456789abcdef\s出现的情况。如果某些字符不在此模式中,则不会通过

编辑:

增加代码以防不通过,将打印所有无效的出现

于 2014-01-07T19:14:47.663 回答
1
def check (pattern, allowed):
    return not set(pattern) - set(allowed)
于 2014-01-07T19:15:51.963 回答