my regex is not catching required pattern in text?

Viewed 52

I am trying to extract duration using regex,

Example text,

text = "Google, Inc 09/19 - 09/20 CA, USA"

Here, is the regex I have,

pattern = fr"""
(?:
  (
    \d\d(?:\.|\/)\d\d\d\d|
    (?:{months_abr})?
    (?:{months_exp})?
    (?:
      (?:[\s\.\/\-]?\d{{2,4}})
    )
  )\s*(?:\-|to|\s)\s*
  (
    \d\d(?:\.|\/)\d\d\d\d|
    (?:{months_abr})?
    (?:{months_exp})?
    (?:
      (?:[\s\.\/\-]?\d{{2,4}})
    )|
    current|present|till\s?\-?date|till\s?\-?now|till\s?\-?date|to\s\-?present|until\s?\-?now|till\s?\-?now
  )
)"""

find_all = re.findall(
    pattern, text, flags=re.MULTILINE | re.VERBOSE | re.IGNORECASE
)

The output I am getting,

[('/19', '09')]
1 Answers

You can use

pattern = fr"""
(?<!\d)                          # A position not immediately preceded with digit
(                                # Group 1
  (?:\d?\d[./])?\d\d(?:\d\d)?    # one or two digits and . or / (optionally), two or four digits
  |                              # or
  (?:{months_abr}|{months_exp}) [\s./-]? \d\d(?:\d\d)? # month, space/dot/slash/hyphen and then two/four digits
)                                # end of Group 1 
\s*(?:-|to)\s*                   # - or "to" enclosed with 0+ whitespaces
(                                # Group 2
    (?:\d?\d[./])?\d\d(?:\d\d)?  
  |
    (?:{months_abr}|{months_exp}) [\s./-]?\d\d(?:\d\d)?
  |
    current|present|(?:un)?till\s?-?(?:date|now|date)|to\s-?present # some alternatives denoting time
)
"""

See the Python demo. Output: [('09/19', '09/20')].

See the regex demo.

Note: I decided to use \d\d instead of \d{2} to keep the code shorter since inside f-strings you need to use {{ and }} to define literal curly braces, and they make the string look ugly here.

Related