Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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 - Fatal编程技术网

Python 返回空值的正则表达式

Python 返回空值的正则表达式,python,regex,Python,Regex,我已经在我的Vscode python文件中编写了以下代码 import os import re filecontent=[] new_list=[] """Placeholder, change, rename, remove... """ for file in os.listdir("resources/"): if file.endswith(".txt"):

我已经在我的Vscode python文件中编写了以下代码

import  os
import  re
filecontent=[]
new_list=[]
"""Placeholder, change, rename, remove... """
for file in os.listdir("resources/"):
    if file.endswith(".txt"):
        with open(os.path.join("resources/", file), "r") as files:
            filecontent = files.read()
            new_list.append(filecontent)
regex = re.compile(r'[\^======================$]*^Username:(\w+)')
for items in new_list:
    print(regex.findall(items))
我的文本文件的结构是

======================
Username:apple
email:apple@gmail.com
phonenumber:8129812891
address:kapan
======================
======================
Username:apple
email:apple@gmail.com
phonenumber:8129812891
address:kapan
======================
Username:apple
email:apple@gmail.com
phonenumber:9841898989
address:kapan
======================
Username:apple
email:apple@gmail.com
phonenumber:1923673645
address:kapan
======================
当我在在线正则表达式检查器中验证它时。它很好用。但当我在应用程序中运行它时,它会返回空列表。
[1]:
我在这里做错了什么?

这里没有必要匹配
==
。您只需搜索用户名并返回结果

您还可以删除
re.compile()
并只运行
re.findall(r'Username:\w+',items)



在在线正则表达式检查器中,您使用的是标志
gm
。但是在代码中,您不会传递任何标志来重新编译。如果不使用多行标志编译正则表达式,$和^。
with open('test.txt', 'r') as file:
    data = file.read()
    print(re.findall(r'Username:(\w+)', data))
    print(re.findall(r'Username:\w+', data))


#['apple', 'apple', 'apple', 'apple']
#['Username:apple', 'Username:apple', 'Username:apple', 'Username:apple']