1

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']
user14932992
  • 19
  • 1
  • 6

2 Answers2

1

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 function re.search, instead of using re.sub to remove the rest of the string, plus this will be more efficient.

import re


CommonPrefixes = [{'Prefix': 'BA/BMF/ABCDEJF/'}, {'Prefix': 'AG/CRBA_CORE/ABCDEJF/'}, {'Prefix': 'DC/KAT/pages-modified/'}]

res = [re.search(r"/([\w_-]+)/$",x["Prefix"]).group(1) for x in CommonPrefixes]

print(res)

Please beware that this might error if some of your CommonPrefixes don't match, so you might want to add a bit of error handling if required.

Gugu72
  • 2,052
  • 13
  • 35
0

Maybe try re.search() and Named Groups?

res = [re.search(r”.+/.+/(?P<result>.+)/”, x[“Prefix”])[“result”] for x in CommonPrefixes]
Ilya
  • 5
  • 5