Python search for a start hex string, save the hex string after that to a new file
<p>PYTHON</p>

<p>I would like to open a text file, search for a HEX pattern that starts with 45 3F, grab the following hex 6 HEX values, for example 45 4F 5D and put all this in a new file. I also know that it always ends with 00 00.</p>

<p>So the file can look like: bla bla sdsfsdf 45 3F 08 DF 5D 00 00 dsafasdfsadf 45 3F 07 D3 5F 00 00 xztert</p>

<p>And should be put in a new file like this:
08 DF 5D 
07 D3 5F </p>

<p>How can I do that?</p>

<p>I have tried:</p>

<pre><code>output = open('file.txt','r')
my_data = output.read()
print re.findall(r"45 3F[0-9a-fA-F]", my_data)
</code></pre>

<p>but it only prints:</p>

<p>[]</p>

<p>Any suggestions?</p>

<p>Thank you :-)</p>

<p>Here's a complete answer (Python 3):</p>

<pre><code>with open('file.txt') as reader:
    my_data = reader.read()

matches = re.findall(r"45 3F ([0-9A-F]{2} [0-9A-F]{2} [0-9A-F]{2})", my_data)
data_to_write = " ".join(matches)
with open('out.txt', 'w') as writer:
    writer.write(data_to_write)
</code></pre>

<p><code>re.findall</code> returns the capturing group, so there's no need to clear out '45 3F'.</p>

<p>When dealing with files, use <code>with open</code> so that the file descriptor will be released when indentation ends.</p>

<p>if you want to accept the first two octets dynamically:</p>

<pre><code>search_string = raw_input()
regex_pattern = search_string.upper() + r" ([0-9A-F]{2} [0-9A-F]{2} [0-9A-F]{2})"
matches = re.findall(regex_pattern, my_data)
</code></pre>

python