简体   繁体   中英

regex to match a pattern multiple times

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.

Use + to match the pattern one or more times.

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

Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM