使用正则表达式提取文件名末尾的版本号

时间:2019-05-23 14:00:47

标签: python regex string

我有一个文件名列表,其中一些文件名以版本号结尾。我正在尝试使用单个正则表达式提取版本号:

 // The code below will retrieve everything in the "info" column and print it to console
 // This prints "Nails Salon" x 5, "Restaurant" x3 and "Coffee Shop" x 7 in the order that they were scanned (Unorganised)
 // What block of code could I make to display what PFuser.current currently has in their parse?
 // E.g. PFUser has scanned "Nail Salon" 5 Times, "Restaurant" 3 time etc etc

    let infoCheck = PFQuery(className: "UserQRCodes")
    infoCheck.whereKey("info", contains: "")
    infoCheck.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if let error = error {

            print(error.localizedDescription)
        } else if let objects = objects {

            print(objects)
        }

    }

// To retrieve everything the USER has scanned and display it as String on the APP


let query = PFQuery(className: "UserQRCodes")
    query.whereKey("userName", equalTo: PFUser.current()!)
    query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if let error = error {
            //log details of the failure
            print(error.localizedDescription)
        } else if let objects = objects {
            let stampees: Int = objects.count

            let totalStampees = String(stampees)
            self.stampeesCollectedLabel.text = totalStampees
            print(objects.count)
        }

    }


    // Do any additional setup after loading the view.
}

到目前为止,我发现以下正则表达式将其与扩展名一同提取:

filename.doc --> NULL
filename.1.0.doc --> 1.0
filename.2.0.pdf --> 2.0
filename.3.0.docx --> 3.0

但是我宁愿没有扩展名。因此,我要搜索的是[0-9]+\.[0-9]+\.(docx|pdf|rtf|doc|docm)$ ,它刚好在字符串中最后一个点出现之前,但是我找不到该怎么做的。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

  

我要搜索的是[0-9]+\.[0-9]+就在字符串中最后一个点之前出现

您可以使用

r'[0-9]+\.[0-9]+(?=\.[^.]*$)'

请参见regex demo

详细信息

  • [0-9]+\.[0-9]+-1个以上数字,.和1个以上数字
  • (?=\.[^.]*$)-一个正向超前查询,需要.,然后是.以外的0+个字符,并且字符串的结尾立即位于当前位置的右边。

请参见regex graph

enter image description here

答案 1 :(得分:0)

Python正则表达式具有named groups

  

一个更重要的功能是命名组:组可以用名称来引用,而不是用数字来引用。

     

命名组的语法是特定于Python的扩展名之一:(?P ...)。名称显然是该组的名称。命名组的行为与捕获组完全相同,并且将名称与组相关联。处理捕获组的match对象方法都接受以数字表示组的整数或包含所需组名称的字符串。命名的组仍具有编号,因此您可以通过两种方式检索有关组的信息:

>> p = re.compile(r'(?P<word>\b\w+\b)')
>> m = p.search( '(((( Lots of punctuation )))' )
>> m.group('word')
'Lots'
>> m.group(1)
'Lots'

因此,您可以将正则表达式修改为:

(?P<version>[0-9]+\.[0-9]+)\.(docx|pdf|rtf|doc|docm)$

并使用:

found.group('version')

从找到的正则表达式匹配项中选择版本。

答案 2 :(得分:0)

试试这个-

import re

try:
    version = [float(s) for s in re.findall(r'-?\d+\.?\d*', 'filename.1.0.doc')][0]
    print(version)
except:
    pass

在这里,如果有数字,则将其存储在变量版本中,否则将通过。

这应声工作! :)

相关问题