0

I'm trying to create a regular expression that will detect when someone says "2 weeks from today, 2 days from today, etc.) Someone can also replace today with now. My current regular expression looks like this:

(re.compile(
    r'''^
            ((?P<weeks>\d+) \s weeks?)?
            [^\d]*
            ((?P<days>\d+) \s days?)?
            [^\d]*
            ((?P<hours>\d+) \s hours?)?
            [^\d]*
            ((?P<minutes>\d+) \s minutes?)?
            [^\d]*
            ((?P<seconds>\d+) \s seconds?)?
            \s
            from  [today, now]
        ''',
    (re.VERBOSE | re.IGNORECASE)),
 lambda m: datetime.datetime.today() + datetime.timedelta(
     days=int(m.group('days') or 0),
     seconds=int(m.group('seconds') or 0),
     minutes=int(m.group('minutes') or 0),
     hours=int(m.group('hours') or 0),
     weeks=int(m.group('weeks') or 0)))

Whenever I run this regex, I get null because it can't detect "2 weeks from today" or something similar. How can I make it so that the output is anything 2 * [days, seconds, minutes, hours, weeks] from today or now?

user2896120
  • 3,180
  • 4
  • 40
  • 100
  • What's you input string? – U13-Forward Jan 13 '20 at 08:09
  • `[today, now]` => `\s+(?:today|now)`. And `[^\d]` = `\D`. – Wiktor Stribiżew Jan 13 '20 at 08:09
  • The [Stack Overflow `regex` tag info page](/tags/regex/info) contains some common beginner mistakes, including this one. – tripleee Jan 13 '20 at 08:11
  • @U10-Forward-ReinstateMonica input string can be anything from 2 weeks from today to 2 hours from now. It just needs to follow that pattern and output the result "from now" – user2896120 Jan 13 '20 at 08:13
  • 1
    `\s+(?:today|now)` [solves the problem](https://regex101.com/r/jbrQEV/1), which you stated is *I get null because it can't detect "2 weeks from today"*. You may further enhance it, say, add word boundaries, etc. You need to update the question to explain the *real* issue and provide some example(s) with expected output. – Wiktor Stribiżew Jan 13 '20 at 08:14

0 Answers0