Home > Software design >  regex to match a pattern multiple times
regex to match a pattern multiple times

Time:12-14

i have this following string values

AAA_POERAS::ZNCDAd_EROS_NOW_X_SHRIAPP_Z_DONTKNOW_J1_Z_SUITS_8907_11
BBB_POERAS::ZNCDAd_EROS_NOW_Q_SHRIAPP67_Y_DONTKNOW_J2_Y_THERE_MLA_WHICH_8906_86_25_01

Using regex how to extract as below, get rid of the last two digits.

AAA_POERAS::ZNCDAd_EROS_NOW_X_SHRIAPP_Z_DONTKNOW_J1_Z_SUITS_8907
BBB_POERAS::ZNCDAd_EROS_NOW_Q_SHRIAPP67_Y_DONTKNOW_J2_Y_THERE_MLA_WHICH_8906

The regex used (\_\d{1,2})$ only matches one patern eg. _11 or _01. i want to match _25 and _86 as well.?

Help needed.

CodePudding user response:

Use to match the pattern one or more times.

re.sub(r'(\_\d{1,2}) $', '', string)

Demo

CodePudding user response:

Use

re.sub(r'(?:_[0-9]{2}) $', '', input_string)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (?:                      group, but do not capture (1 or more times
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    _                        '_'
--------------------------------------------------------------------------------
    [0-9]{2}                 any character of: '0' to '9' (2 times)
--------------------------------------------------------------------------------
  )                        end of grouping
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
  • Related