Python regex similar expressions
<p>I have a file with two different types of data I'd like to parse with a regex; however, the data is similar enough that I can't find the correct way to distinguish it.</p>

<p>Some lines in my file are of form:</p>

<pre><code>AED=FRI
AFN=FRI:SAT
AMD=SUN:SAT
</code></pre>

<p>Other lines are of form</p>

<pre><code>AED=20180823
AMD=20150914
AMD=20150921
</code></pre>

<p>The remaining lines are headers and I'd like to discard them.  For example</p>

<pre><code>[HEADER: BUSINESS DATE=20160831]
</code></pre>

<p>My solution attempt so far is to match first three capital letters and an equal sign, </p>

<pre><code>r'\b[A-Z]{3}=\b'
</code></pre>

<p>but after that I'm not sure how to distinguish between dates (eg 20180823) and days (eg FRI:SAT:SUN).</p>

<p>The results I'd expect from these parsing functions:</p>

<pre><code>Regex weekday_rx = new Regex(&lt;EXPRESSION FOR TYPES LIKE AED=FRI&gt;);
Regex date_rx = new Regex(&lt;EXPRESSION FOR TYPES LIKE AED=20160816&gt;);


weekdays = [weekday_rx.Match(line) for line in infile.read()]
dates = [date_rx.Match(line) for line in infile.read()]
</code></pre>

<p>Use pipes to express alternatives in regex. Pattern '[A-Z]{3}:[A-Z]{3}|[A-Z]{3}' will match both ABC and ABC:ABC. Then use parenthesis to group results:</p>

<pre><code>import re

match = re.match(r'([A-Z]{3}:[A-Z]{3})|([A-Z]{3})', 'ABC:ABC')
assert match.groups() == ('ABC:ABC', None)

match = re.match(r'([A-Z]{3}:[A-Z]{3})|([A-Z]{3})', 'ABC')
assert match.groups() == (None, 'ABC')
</code></pre>

<p>You can research the concept of named groups to make this even more readable. Also, take a look at the docs for the match object for useful info and methods.</p>

python regex