user13784158
user13784158

Reputation:

regex returning null value

I have wrote following code in my Vscode python file.

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))

And structure of my text file is

======================
Username:apple
email:[email protected]
phonenumber:8129812891
address:kapan
======================
======================
Username:apple
email:[email protected]
phonenumber:8129812891
address:kapan
======================
Username:apple
email:[email protected]
phonenumber:9841898989
address:kapan
======================
Username:apple
email:[email protected]
phonenumber:1923673645
address:kapan
======================

When i verify it in online regex checker. It works fine. But when i run it in my app it returns empty list.
[1]: https://i.sstatic.net/2Mrlb.png What is the wrong thing i am doing here?

Upvotes: 0

Views: 182

Answers (1)

PacketLoss
PacketLoss

Reputation: 5746

There is no need to match the === here. You can just search the username and return the result.

You can also remove your re.compile() and just run re.findall(r'Username:\w+', items)


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']

Upvotes: 1

Related Questions