Regex to extract two dates out of a date range
<p>I have a date range and I want to extract the two dates, this is an example string:</p>

<pre><code>Sep 25-28, 2016
</code></pre>

<p>and I'd like to have two regular expressions, one that matches:</p>

<pre><code>Sep 25, 2016
</code></pre>

<p>and the other that matches:</p>

<pre><code>Sep 28, 2016
</code></pre>

<p>But then I'd like that also matches:</p>

<pre><code>Sep 29-Oct 2, 2016
</code></pre>

<p>This is what I have built so far:</p>

<pre><code>(?P&lt;date&gt;\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|[0-9]|1[0-2]) (\d|[0-2][0-9]|3[0-1])(\s|\.|-)(:?\d|[0-2][0-9]|3[0-1]),?(\s|\.|-)\b\d{1,4}\b)
</code></pre>

<p>But of course matches the whole range.</p>

<p>Any help?</p>

<p>I would recommend using different regex for each possibility, and test them in order.  This will result in a much simpler program (with test cases).  Otherwise, the regex would be monstrous.</p>

<pre><code>import re

RE1 = re.compile(r"(\w+)\s*(\d+)\,\s+(\d+)")  # Month day, year                              
RE2 = re.compile(r"(\w+)\s*(\d+)\-(\d+)\,\s+(\d+)")  # Month day-day, year                   
RE3 = re.compile(r"(\w+)\s*(\d+)\-(\w+)\s+(\d+)\,\s+(\d+)")  # Month day - Month day, year                                                                                                   


def date_interval(t):
  match1 = RE1.match(t)
  match2 = RE2.match(t)
  match3 = RE3.match(t)
  if match1:
    month1 = month2 = match1.group(1)
    day1 = day2 = match1.group(2)
    year = match1.group(3)
  elif match2:
    month1 = month2 = match2.group(1)
    day1 = match2.group(2)
    day2 = match2.group(3)
    year = match2.group(4)
  elif match3:
    month1 = match3.group(1)
    day1 = match3.group(2)
    month2 = match3.group(3)
    day2 = match3.group(4)
    year = match3.group(5)
  else:
    month1 = month2 = day1 = day2 = year = ''
  return ( day1, month1, day2, month2, year )


texts = (
  'Sep 25, 2016',
  'Oct 12-23, 2017',
  'Jan 15-Feb 26, 2018',
)

for t in texts:
  print t, date_interval(t)
</code></pre>

<p>this prints (python2)</p>

<pre><code>Sep 25, 2016 ('25', 'Sep', '25', 'Sep', '2016')
Oct 12-23, 2017 ('12', 'Oct', '23', 'Oct', '2017')
Jan 15-Feb 26, 2018 ('15', 'Jan', '26', 'Feb', '2018')
</code></pre>

<p>You could easily extend the program if you need to parse dates with different years.</p>

<p>You could also replace <code>\w</code> with the months, as you did in your post (<code>Jan|Feb|...</code>).  </p>

python regex