简体   繁体   中英

How do I get the last part of a string before a number shows up with regex?

I'm using Python 3.8 to loop through each string in a list. I want to extract only the colors at the end.

As it seems that the colors are divided from the model's names by a date (or at least a word with some digits in it), I'm trying to use the python librairy 're' to split the strings. But I can't figure out how to start from the end rather than the beginning?

Jackson_Phil_Demmel_Demmelition_King_V_2010s_Standard_Finish
Paul_Reed_Smith_513_2012_Black_Slate
Paul_Reed_Smith_408_TM_with_Artist_Package_2013_Whale_Blue
Paul_Reed_Smith_408_MT_2013_Livingston_Lemondrop
Paul_Reed_Smith_20th_Anniversary_12-string_with_10-top_2005_Yellow_Burst
Paul_Reed_Smith_Brent_Mason_Signature_2Epiphone_EA-255_Casino_1970s_Walnut
Epiphone_Limited_Edition_Wilshire_Pro_2000s
Epiphone_Coronet_1966_Cherry010s_Transparent_Finish
Epiphone_Matt_Heafy_Signature_7-String_Les_Paul_Custom
B.C._Rich_Mockingbird_late_80s_Black_Sparkle
GandL_ASAT_Classic_1990s_Solid_Finish_or_Sunburst

how do I split those strings to only keep the end result?

Something like '.*[0-9]s?_(.*)' should work, then take the group.

eg:

import re

for s in [
    'Jackson_Phil_Demmel_Demmelition_King_V_2010s_Standard_Finish',
    'Paul_Reed_Smith_513_2012_Black_Slate',
    'Paul_Reed_Smith_408_TM_with_Artist_Package_2013_Whale_Blue',
    'Paul_Reed_Smith_408_MT_2013_Livingston_Lemondrop',
    'Paul_Reed_Smith_20th_Anniversary_12-string_with_10-top_2005_Yellow_Burst'
    'Paul_Reed_Smith_Brent_Mason_Signature_2Epiphone_EA-255_Casino_1970s_Walnut',
    'Epiphone_Limited_Edition_Wilshire_Pro_2000s',
    'Epiphone_Coronet_1966_Cherry010s_Transparent_Finish',
    'Epiphone_Matt_Heafy_Signature_7-String_Les_Paul_Custom',
    'B.C._Rich_Mockingbird_late_80s_Black_Sparkle',
    'GandL_ASAT_Classic_1990s_Solid_Finish_or_Sunburst']:

    m = re.match('.*[0-9]s?_(.*)',s)
    color = m.groups()[0] if m else 'NONE'

    print(f'{s}:\t{color}')

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