python - 使用正则表达式搜索特定文件

标签 python regex python-3.x

我正在 try catch 文件夹中文件名中的两个特定单词/字符序列。到目前为止,我所得到的在 https://regex101.com/ 上给出了正确的输出但不在我正在使用的脚本中。

这是我正在使用的文件名类型:

Bjørn Stallaresvei s 10013.pdf

Københavngaten 1 L. 8.pdf

这是我到目前为止想出的正则表达式:

((?<=\s)[a-zA-Z\.]+(?=[\s0-9]+\.pdf))|((?<=\s)[0-9]+(?=.pdf))

我试图在第一行捕获“s”和“10013” - 其中“s”是标识符,10013 是 ID。

第二行也一样,L.是标识符,8是ID。

这只是一个示例代码:

import re

string_1 = "Stallaresvei s 10013.pdf"

regexp = r"(((?<=\s)[a-zA-Z\.]+(?=[\s0-9]+\.pdf))|((?<=\s)[0-9]+(?=.pdf)))"
m = re.search(regexp, string_1)

print(m)

输出仅显示找到的一个匹配项:

<_sre.SRE_Match object; span=(13, 14), match='s'>

最佳答案

您可以删除捕获括号并将正则表达式与 re.findall 一起使用:

r'(?<=\s)[a-zA-Z.]+(?=[\s0-9]+\.pdf)|(?<=\s)[0-9]+(?=\.pdf)'

请参阅online Python 3 demo :

import re
string_1 = "Stallaresvei s 10013.pdf"
regexp = r"(?<=\s)[a-zA-Z.]+(?=[\s0-9]+\.pdf)|(?<=\s)[0-9]+(?=\.pdf)"
m = re.findall(regexp, string_1)
print(m) # => ['s', '10013']

另一种方法是重写模式并将这些位捕获为 2 组,请参阅 another demo :

import re
string_1 = "Stallaresvei s 10013.pdf"
regexp = r"\s([a-zA-Z.]+)\s+([0-9]+)\.pdf"
m = re.search(regexp, string_1)
if m:
    print([m.group(1), m.group(2)])

这里,

  • \s - 匹配空格
  • ([a-zA-Z.]+) - 捕获组 1 匹配 1+ ASCII 字母或
  • \s+ - 1 个以上空格
  • ([0-9]+) - 捕获组 2 匹配 1+ ASCII 数字
  • \.pdf - 仅匹配 .pdf 子字符串。

关于python - 使用正则表达式搜索特定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41242105/

相关文章:

python - 如何使用带参数的任务计划程序运行 python 脚本

python - 遍历类似 excel 的字符组合范围

python - 为什么返回的字符串可以解释为 python 中的函数?

python - Apscheduler 没有列出触发器

匹配 {0} 的 JavaScript 正则表达式

java性能问题-正则表达式VS内部String方法

python-3.x - 如何修复 'Can' t 分配请求的地址'。即使我在 mac 上用 python 尝试了许多不同的端口

python - Dask:为什么CPU使用率突然下降?

python - torch.no_grad() 影响模型精度

MySQL 正则表达式列表