Make Regex for following pattern

I want to make a regex that can fulfill both conditions.

DELIVERY INFO AVY-21720913/05-APR-22

DELIVERY INFO : AVY21784045/

it can take both values until slash "/" appears.

INPUT:

In a string

DELIVERY INFO AVY-21720913/05-APR-22

DELIVERY INFO : AVY21784045/

OUTPUT:

DELIVERY INFO AVY-21720913

DELIVERY INFO : AVY21784045

>Solution :

Assuming there be at most one forward slash, I would suggest just using string split() here:

inp = ["DELIVERY INFO AVY-21720913/05-APR-22", "DELIVERY INFO : AVY21784045/", "DELIVERY INFO : ABC"]
output = [x.split('/')[0] for x in inp]
print(output)

This prints:

['DELIVERY INFO AVY-21720913',
 'DELIVERY INFO : AVY21784045',
 'DELIVERY INFO : ABC']

If you really wanted to use regex, then we can do a replacement on the pattern /.*$:

inp = ["DELIVERY INFO AVY-21720913/05-APR-22", "DELIVERY INFO : AVY21784045/", "DELIVERY INFO : ABC"]
output = [re.sub(r'/.*$', '', x) for x in inp]
print(output)  # same output as above

Leave a Reply