Need help with Regex expression, which i'm trying to work on. Below is the example that i'm trying to work on
Code
import re
CommonPrefixes = [{'Prefix': 'BA/BMF/ABCDEJF/'}, {'Prefix': 'AG/CRBA_CORE/ABCDEJF/'}, {'Prefix': 'DC/KAT/pages-modified/'}]
res = [re.sub("(^\w+/)|(^\w+\/|/)|(/$)",'',x["Prefix"]) for x in CommonPrefixes]
print(res)
Output I'm getting is below
OutPut
['BMFABCDEJF', 'CRBA_COREABCDEJF', 'KATpages-modified']
Output I'm looking for
Expected output
['ABCDEJF', 'ABCDEJF', 'pages-modified']
Looks like you want the last substring between 2 slashes for each of your strings. Here's the Regex you want to use:
/([\w_-]+)/$. However, you'll want to use that regex with the functionre.search, instead of usingre.subto remove the rest of the string, plus this will be more efficient.Please beware that this might error if some of your
CommonPrefixesdon't match, so you might want to add a bit of error handling if required.