Trouble finding a regular expression with lookahead/ lookbehind funcftion

I've been having an issue with getting my regular expression right. I'm looking to get just specific numbers in the following strings. For example, the following are some strings along with the regular expression I'm using

matcher = re.compile(r'(?<=[/\- ])([0-9]+)')

string = 'Redundant 100/70/50/50-0/0/0/0; EX-SEP ANN IMPLANT MAX.                     '
string2 = 'Big High 200/40/40/0/0-80/60/40/0/0; EX-WP 9months 7.                                                                                                                                                                                                 '

The outcome from this is

['100', '100', '85', '50', '0', '0', '0', '0']
['100', '80', '50', '0', '0', '80', '60', '40', '0', '0', '9', '7']

I'd like to figure out a way to get only the numbers next to a '/' but not the '9' and '7' in the second string for instance. I can't find a way to do this and have tried using a lookbehind expression but can't get just the numbers I want without also retrieving other numbers in my strings.

This is all new to me and I'd really appreciate any help on why I'm not getting my expected answers for each string

1 answer

  • answered 2020-10-20 16:22 Wiktor Stribiżew

    You can match digit sequences close to / or - using

    (?<=[/-])[0-9]+|[0-9]+(?=[/-])
    

    See the regex demo.

    Details

    • (?<=[/-])[0-9]+ - one or more digits that have a / or - in front
    • | - or
    • [0-9]+(?=[/-]) - one or more digits that have a / or - right after.