gpt4 book ai didi

python - 正则表达式 Python

转载 作者:行者123 更新时间:2023-11-28 21:56:27 25 4
gpt4 key购买 nike

我有以下 python 代码,它将尝试读取输入文件并找到给定正则表达式的以下实例:

[fF][eE][bB]([1-2][0-9]|[0-9]

我写了下面的python代码

#!/usr/bin/python
import re
import sys

textFile = open(sys.argv[1], 'r')
fileText = textFile.read()
textFile.close()
matches = re.findall("[fF][eE][bB] ([1-2][0-9]|[0-9])",fileText)
print matches

我的输入文件是:

1 2 3 the
the quick 2354
feb 1
feb 0
feb -10
feb23
feb 29
feb 3
february 10

但是,当我运行我的代码时,我得到以下输出:['1','29', '3']

我希望我的输出更像 ['feb 1', 'feb 29', 'feb 3']

我不太确定我做错了什么。任何帮助将不胜感激。

最佳答案

你应该read the documentation . re.findall 仅在表达式中存在时返回捕获组。您应该简单地从正则表达式中删除捕获组:

matches = re.findall("[fF][eE][bB] (?:[1-2][0-9]|[0-9])",fileText)
^^

也就是说,这个正则表达式也将匹配 feb 0,所以你可能想使用

[fF][eE][bB] (?:[1-2][0-9]|[1-9])
^

相反。

现在,如果您使用 re.IGNORECASE(使正则表达式匹配大写和小写字符),并且如果您使用循环读取文件内容(这对于大文件更有效)。此外,原始正则表达式模式是一种很好的做法:

with open(sys.argv[1], 'r') as textFile:
for line in textFile:
matches = re.match(r"feb (?:[1-2][0-9]|[1-9])", line, re.IGNORECASE)
if matches:
print matches.group()

当然,如果最后需要一个列表,您也可以将匹配项放在一个列表中。

关于python - 正则表达式 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com