python - 使用正则表达式查找 1 个字母和 2 个数字

标签 python regex python-3.x

我最近一直在写一个程序,其中一部分要求我从字符串中获取信息。我需要找到 1 个字母后跟 2 个数字(例如 S07)的位置,但我无法计算出它的正则表达式。

def get_season(filenames):
    pattern = "^[a-zA-z]{1}[\d]{2}$"
    found = re.search(filenames[0], pattern)
    season_name = found.string
    season = season_name[1:3]
    print(season)

我知道这个信息在字符串中,但它一直给我“无”作为回应

(我不太确定代码部分的格式是否正确,在预览中它显示在同一行,但我程序中的缩进是正确的)

最佳答案

您将参数交换到 re.search()。第一个参数是模式,而不是要匹配的字符串:

found = re.search(pattern, filenames[0])

你的图案也太宽了; A-z 也匹配 Z(大写)和 a(小写)之间的所有内容。正确的模式是:

pattern = "^[a-zA-Z]\d{2}$"

其中 {1} 是默认值,所以我省略了它。

如果您将其与文件名进行匹配,您可能不想使用开始或结束 anchor ,这会将匹配限制为仅精确字符串:

>>> re.search("^[a-zA-Z]\d{2}$", "S07").string
'S20'
>>> re.search("^[a-zA-Z]\d{2}$", "S07E01 - Meet the New Boss.avi") is None
True
>>> re.search("^[a-zA-Z]\d{2}$", "S07E01 - Meet the New Boss.avi") is None
True
>>> re.search("[a-zA-Z]\d{2}", "S07E01 - Meet the New Boss.avi").string
'S07E01 - Meet the New Boss.avi'

并且您想使用 .group() 来获取匹配的部分,而不是 string(这是原始输入字符串):

>>> re.search("[a-zA-Z]\d{2}", "S07E01 - Meet the New Boss.avi").group()
'S07'

如果您只想要数字,则需要添加一个组,然后选择它。您创建一个带括号的捕获组:

>>> re.search("[a-zA-Z](\d{2})", "S07E01 - Meet the New Boss.avi").group(1)
'07'

这将选择第一组 (.group(1)),这是 2 位数字部分周围的括号。

关于python - 使用正则表达式查找 1 个字母和 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003025/

相关文章:

linux - 如何通过套接字将 `eof` 信号发送到在远程 shell 中运行的命令?

Python 3 - 基于字符串的字典搜索列表

python - 在Raspberry pi 3中安装openCV失败

`x...(a and b)...y` 的正则表达式在有限长度内?

javascript - 如何在 Node JS 中执行正则表达式匹配?

regex - PCRE:回溯中不允许反向引用?

python - Python 3项目结构的最佳实践

python - 如何在没有闲置的情况下安装python?

python - 如何在Python 3.5中的socket.sent()的字节字符串中添加\n

python - 使用递归获取所有树子项