Regex根据文件扩展名列表抓取文件名



我有以下Regex,它似乎可以在提供的列表中识别字符串,但我需要从识别的字符串到令牌的开始抓取一切,无论其中有什么字符。

^.*?b(png|dll|exe|docx|pdf)b.*$

我正在搜索以下测试字符串:

The filename is test.exe will I be able to find it
The file name is bob.png
the file name is my filename.pdf, we love pdfs
the file name is question.png
this is my word file.docx
this is my odd file[.]png

我想找到:

test.exe
bob.png
filename.pdf
question.png
file.docx
file[.]png

我也刚刚意识到…"我们爱pdf"这种方式也可能存在问题。如果有任何帮助就太好了

你要求:

查找扩展名

前面的非空格字符。
/^.*?b(S+(?:png|dll|exe|docx|pdf))b.*$/gm

演示:https://regex101.com/r/aJ3gV5/1

以上在python中工作,以说明两者的区别。注意,底线上只有一个匹配。

>>> s = """The filename is test.exe will I be able to find it
... The file name is bob.png
... the file name is my filename.pdf, we love pdfs
... the file name is question.png
... this is my word file.docx
... this is my odd file[.]png file2[.]png"""
>>> re.findall(r"(?m)^.*?b(S+(?:png|dll|exe|docx|pdf))b.*$", s)
['test.exe', 'bob.png', 'filename.pdf', 'question.png', 'file.docx', 'file[.]png']

只是为了说明下面相同输入的正则表达式:

>>> re.findall(r"(S+(?:png|dll|exe|docx|pdf))", s)
['test.exe', 'bob.png', 'filename.pdf', 'question.png', 'file.docx', 'file[.]png', 'file2[.]png']

我推荐的:

匹配完整的行是没有意义的,除非您只想要每行的第一个匹配。你可以用这个找到更多的结果:

/(S+(?:png|dll|exe|docx|pdf))/g

演示:https://regex101.com/r/aJ3gV5/2

因为你在另一条评论中说你可能会使用python,下面是它在python中的工作:

>>> s = """The filename is test.exe will I be able to find it
... The file name is bob.png
... the file name is my filename.pdf, we love pdfs
... the file name is question.png
... this is my word file.docx
... this is my odd file[.]png"""
>>> re.findall(r"(S+(?:png|dll|exe|docx|pdf))", s)
['test.exe', 'bob.png', 'filename.pdf', 'question.png', 'file.docx', 'file[.]png']
编辑:

也可以通过在正则表达式的开头添加:

来强制匹配点。
S+.S*
/(S+.S*(?:png|dll|exe|docx|pdf))/g

演示:https://regex101.com/r/aJ3gV5/4

最新更新