How to properly test for valid characters in pattern, possibly using character arrays or some other method(regex)

StackOverflow https://stackoverflow.com/questions/20979835

質問

I have a problem that I can't seem to figure out in Python. I have a pattern that need to match any of the characters in a character array. If it doesn't, then there is a problem. So here are my examples:

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 0016 05e0 0156 0055 0016 0e41"

allowedCharacters = "123456789abcdef"

So my goal is to see if the pattern conforms to the allowed characters. In C# I did the following, but I can't figure out how to get this done in Python.

Here is my current code.

        # 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`

Any ideas/suggestions/code examples are welcome.

Thanks.

役に立ちましたか?

解決

Try this code:

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)

It will search in the string for the 0123456789abcdef\s occurrences. If some character is not in this pattern, then it won't pass

EDIT:

Increased the code in case it won't pass, will print all the occurrences which are invalid

他のヒント

def check (pattern, allowed):
    return not set(pattern) - set(allowed)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top