0

我想在我的 python 表达式中添加一个可选部分:

myExp = re.compile("(.*)_(\d+)\.(\w+)")

所以如果我的字符串是 abc_34.txt,result.group(2) 是 34 如果我的字符串是 abc_2034.txt,results.group(2) 仍然是 34

我试过myExp = re.compile("(.*)_[20](\d+)\.(\w+)")

但对于 abc_2034.txt,我的 results.groups(2) 是 034

谢谢FJ

但我想扩展您的解决方案并添加一个后缀。

这样如果我输入 abc_203422.txt,results.group(2) 仍然是 34

我试过 "(.*)_(?:20)?(\d+)(?:22)?.(\w+)") 但我得到 3422 而不是 34

4

3 回答 3

1
strings = [
    "abc_34.txt", 
    "abc_2034.txt",  
]


for string in strings:
    first_part, ext = string.split(".")
    prefix, number = first_part.split("_")

    print prefix, number[-2:], ext


--output:--
abc 34 txt
abc 34 txt



import re

strings = [
    "abc_34.txt", 
    "abc_2034.txt",  
]

pattern = r"""
    ([^_]*)     #Match not an underscore, 0 or more times, captured in group 1
    _           #followed by an underscore
    \d*         #followed by a digit, 0 or more times, greedy
    (\d{2})     #followed by a digit, twice, captured in group 2
    [.]         #followed by a period
    (.*)        #followed by any character, 0 or more times, captured in group 3
"""


regex = re.compile(pattern, flags=re.X)  #ignore whitespace and comments in regex

for string in strings:
    md = re.match(regex, string)
    if md:
        print md.group(1), md.group(2), md.group(3)

--output:--
abc 34 txt
abc 34 txt
于 2013-08-12T23:17:32.370 回答
0
myExp = re.compile("(.*)_(?:20)?(\d+)\.(\w+)")

?:包含在组开头的使其20成为非捕获组,该?组之后使其成为可选。所以(?:20)?意味着“可选匹配20”。

于 2013-08-12T23:12:03.773 回答
0

不确定您是否正在寻找这个,但?它是 0 或 1 次的 re 符号。或 {0,2} 对于最多两个可选的 [0-9] 来说有点笨拙。我会考虑更多。

于 2013-08-12T23:15:19.593 回答