0
>>> line = '\xc2d sdsdfdslkfsdkfjdsf'
>>> pattern_strings = ['\xc2d', '\xe9']
>>> pattern = '|'.join(pattern_strings)
>>> pattern
'\xc2d|\xe9'
>>> import re
>>> re.findall(pattern, line)
['\xc2d']

When I put line in a file and try to do the same regex, it doen't show up anything

def find_pattern(path):
    with open(path) as f:
        for line in f:
            line = line.strip()
            pattern_strings = ['\xc2d', '\xe9'] # or using ['\\xc2d', '\xe9'] doesn't help
            pattern = '|'.join(pattern_strings)
            print re.findall(pattern, line)

where path is a file looked as following
\xc2d sdsdfdslkfsdkfjdsf

I see

\xc2d
[]
d\xa0
[]
\xe7
[]
\xc3\ufffdd
[]
\xc3\ufffdd
[]
\xc2\xa0
[]
\xc3\xa7
[]
\xa0\xa0
[]
'619d813\xa03697'
[]
2
  • Add print line to your app to ensure you are reading file properly Commented Jul 27, 2012 at 20:31
  • yes @Omnga, the file prints the data correctly Commented Jul 27, 2012 at 20:31

2 Answers 2

2

line = "\xc2d bla" is a Python string where `"\xc2d" is a substring with 2 characters in it.

Your file sounds like it has the literal string "\xc2d" in it, which wouldn't match that pattern.

If you'd like to match the literal string, you'd need to match each of its characters (so, escape the slash).

pattern = r"\\xc2d" 
Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to match the literal string with pattern?
Neither does saying "that doesn't helps out".
sorry if you feel bad, but yeah I tried the way you said and it doesn't work
I don't feel bad :). If you'd like help, you need to specify what you tried, and how it didn't work. Just saying "it didn't work" isn't helpful, nor is responding with "what you told me isn't helpful".
ah, sorry about that, I am continuously making updates to code above
|
1

You would need to read file in binary mode f = open("myfile", "rb") to prevent \x conversion, as in Python \xhh represents hex escape characters.

Non-binary reading will fail - check here.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.