英文:
Python regular expression 'BA/BMF/ABCDEJF/
问题
需要帮助的正则表达式部分如下:
[re.sub("(^\w+/)|(^\w+/|/)|(/$)",'',x["Prefix"]) for x in CommonPrefixes]
期望的输出如下:
['ABCDEJF', 'ABCDEJF', 'pages-modified']
英文:
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']
答案1
得分: 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_-]+)/$."
这是您想要使用的正则表达式:/([\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."
然而,您应该使用re.search函数与该正则表达式,而不是使用re.sub来删除字符串的其余部分,这样效率更高。
"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."
请注意,如果您的某些CommonPrefixes不匹配,这可能会出现错误,因此如果需要的话,您可能需要添加一些错误处理。
英文:
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.
答案2
得分: 0
尝试使用 re.search() 和命名分组可能会有帮助:
res = [re.search(r".+/.+/(?P<result>.+)", x["Prefix"])["result"] for x in CommonPrefixes]
英文:
Maybe try re.search() and Named Groups?
res = [re.search(r”.+/.+/(?P<result>.+)/”, x[“Prefix”])[“result”] for x in CommonPrefixes]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论