【问题标题】:I seem not to get it right in regex in python when matching digits匹配数字时,我似乎在 python 的正则表达式中没有正确
【发布时间】:2021-08-28 02:44:39
【问题描述】:

我有一个列表,其中包含镜像文件名的项目。我只想过滤仅包含数字的名称。我似乎没有得到它的权利。即使匹配一个数字似乎也不起作用。是我做的不对吗?任何线索或建议将不胜感激。

代码示例:

import re

pattern = r"^\d.+[.]"
pattern2 = r'\d*'

a = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for i in a:
    if re.match(i, pattern):
        print(i)

【问题讨论】:

  • 模式应该是re.match的第一个参数。请参阅help(re.match) 了解更多信息。
  • 你不需要正则表达式。 Python 字符串有isdigit()。您只需要检查没有扩展名的文件名
  • 另外,re.match 已经从输入开始匹配。这种方法的命名不好,所以我总是使用re.search 来代替锚点。

标签: python regex re


【解决方案1】:

这应该可行:

模式 = r"\d+?.\w+"

或者,如果你想捕获文件名:

模式 = r"(\d+?).\w+"

但如果您的文件名包含“.”,这将不起作用。

【讨论】:

  • 我做了快速列表理解,但它似乎捕获了匹配 ``` a = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"] pattern = r"\d+?.\w+" fin = [j for j in a if re.match(j, pattern)] print(fin) ```
【解决方案2】:

您似乎弄错了re.match函数的参数顺序。

这是我测试过的代码,可以满足您的要求:

# Regex explanation,
# ^ Indicates position at start of a line.
# \d+ Indicates any digit and can be N number of times. Digit is defined as [0-9].
# \. Indicates a literal .
# \w+ Indicates any word and can be N number of times. Word is defined as [a-zA-Z0-9_].
pattern = r'^\d+\.\w+'

files_list = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for file in files_list:
    # The order of arguments for re.match should be, (pattern, string).
    if re.match(pattern, file):
        print(file)

输出:

1000.mp4
110082.mp4
829873.m4a

【讨论】:

  • .m4a 怎么样?
  • @Moses 我已经调整了答案,我错过了。
  • 效果很好。它捕获了所有的扩展!!!
  • 通过一个命令在子目录中帮助删除超过 10000 个文件。事实证明这很有帮助。
  • 很高兴它能帮助您完成任务。
【解决方案3】:

这是一个有效的代码。您可以摆弄正则表达式以获得更好的正则表达式字符串,以便在没有点字符的情况下进行匹配。

import re

pattern = re.compile(r"^[0-9]+.")

a = ["1000.mp4", "test.mp4", "110082.mp4", "829873.m4a"]

for i in a:
    match = re.match(pattern, i)
    if match:
        matched_string = match.group(0)
        string_without_dot = matched_string[0:len(matched_string)-1]
        print(string_without_dot)

【讨论】:

  • 这个捕获.mp4和m4a
猜你喜欢
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多