Python正则表达式 ‘BA/BMF/ABCDEJF/

huangapple go评论46阅读模式
英文:

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&lt;result&gt;.+)/”, x[“Prefix”])[“result”] for x in CommonPrefixes]

huangapple
  • 本文由 发表于 2023年7月13日 15:45:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定