Home > Enterprise >  Match everything before a set of characters but if they aren't present then match everything
Match everything before a set of characters but if they aren't present then match everything

Time:09-21

I have a series of strings some of which have a year string at the end in the format -2022. I'm looking to match everything up to but excluding the - before 4 digit year string but if there is no year present then I would like to return the entire string. The following:

import re
x = "itf-m15-cancun-15-men-2022"
re.search(r"^. ?(?=-\d\d\d\d)", x).group()

Gets me 'itf-m15-cancun-15-men' which I'm looking for. However, the following:

import re
x = "itf-m15-cancun-15-men"
re.search(r"^. ?(?=-\d\d\d\d)", x).group()

Errors as no result is returned. How do I capture everything up to but excluding the - before the 4 digit year string or return the whole string if the year string isn't present?

CodePudding user response:

Add OR end |$ inside your lookahead:

^. ?(?=-\d{4}|$)

See demo at regex101

Alternatively a tempered greedy token can be used like in this demo (a bit less efficient).

CodePudding user response:

Make the (?=-\d\d\d\d) conditional by adding a ? after it. (Tested in JavaScript)

/^. ?(?=-\d\d\d\d)?$/
  • Related