Home > Back-end >  Regex replace last weight unit string
Regex replace last weight unit string

Time:06-01

i'm not familiar with regex. i have one problem to replace only last weight string (1 kg, 2 kg etc) in a long text by regex.

For example : Bombay Red Onion 1kg

will be replace to : Bombay Red Onion

other case :

Bombay Red 2 kg Onion 3kg
Bombay 1 kg Red 2 kg Onion 5 kg

expected output:

Bombay Red 2 kg Onion
Bombay 1 kg Red 2 kg Onion

Anyone can help me? very appreciate if it uses python script.

CodePudding user response:

Try (Regex img

Code implementation:

import re

test_str = ("Bombay Red 2 kg Onion 3kg\n"
    "Bombay 1 kg Red 2 kg Onion 5 kg\n"
    "Bombay Red Onion 1kg\n"
    "Bombay Red Onion 120 kg\n"
    "Bombay Red Onion 12 kg\n"
    "Bombay Red Onion\n")

regex = re.compile(r"\d  ?kg$", flags=re.MULTILINE)

replacedStr = regex.sub("", test_str)
print(replacedStr)

Online demo

  • Related