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です

ありがとうございます

しかし、ソリューションを拡張して接尾辞を追加したいと思います。

abc_203422.txt を配置すると、results.group(2) は 34 のままです

"(.*)_(?:20)?(\d+)(?:22)?.(\w+)") を試しましたが、34 ではなく 3422 が表示されます

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

これを探しているかどうかはわかりませんが?、0 回または 1 回の re 記号です。または {0,2} は、最大 2 つのオプションの [0-9] に対して少しハックです。もっと考えてみます。

于 2013-08-12T23:15:19.593 に答える