Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式问题_Python_Regex_Python 3.x - Fatal编程技术网

Python正则表达式问题

Python正则表达式问题,python,regex,python-3.x,Python,Regex,Python 3.x,我有一个正则表达式,它在一些文本之后得到一些数字 num_output = re.compile(r'only_numbers=([0-9]*)') print(get_numbers.findall(f1)) 我得到的输出是正确的。我正在读的字符串有如下内容 only_numbers = 123456789 我捕获了123456789,但当我输出到屏幕时,我得到以下信息: ['123456789'] 是否仍要从我的输出中删除“[””和“']” with open(filetoread)

我有一个正则表达式,它在一些文本之后得到一些数字

num_output = re.compile(r'only_numbers=([0-9]*)')
print(get_numbers.findall(f1))
我得到的输出是正确的。我正在读的字符串有如下内容

only_numbers = 123456789
我捕获了
123456789
,但当我输出到屏幕时,我得到以下信息:

['123456789']
是否仍要从我的输出中删除“[””和“']”

with open(filetoread) as f1:
f2 = f1.read()
num_output = re.compile(r'only_numbers=([0-9]*)')

感谢您的指导。

re.findall
通过字符串继续重新应用
re.search
,并返回找到的匹配项列表。要获得一个,请自己搜索。请注意没有匹配项的情况

num_output = re.compile(r'only_numbers=([0-9]*)', flags=re.MULTILINE)
try:
    num = num_output.search(f1).group(1)
except AttributeError:
    num = 'not found'
print(num)
在您的文件示例中,如果文件很大,您可能会受益于逐行检查它,这样您就不会一次将所有文件放入内存。我们可以使用
itertools.dropwhile
删除行,直到正则表达式匹配,并使用返回的第一个匹配对象

import re
import itertools

num_output = re.compile(r'only_numbers=(\d*)')

with open('test.txt') as f1:
    try:
        num = next(itertools.dropwhile(lambda m: not m,
            map(num_output.search, f1))).group(1)
    except StopIteration:
        num = 'not found'

print(num)

因为这正是
findall
返回的结果。按照:“返回字符串中模式的所有非重叠匹配,作为字符串列表。”。因此,您只需将结果作为一个列表处理,然后从那里开始。正如idjaw所说,它返回一个字符串列表,因此,如果您希望
findall
返回文件中的所有数字,那么您必须使用for each循环遍历该列表并打印每个元素。我添加了以下f=get_numbers.findall(f1)print(f[0])有没有更好的方法来写我想要实现的目标?我只想以纯文本的形式返回数字。谢谢你的正则表达式与你的示例字符串不匹配…请注意等号周围的空格。你能整理一下吗?