0

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?

1
  • In the online regex checker you are using the flags gm. But in your code you don't pass any flags to re.compile. Your use of $ and ^ will not work as expected if you don't compile the regex using the multiline flag. docs.python.org/3/library/re.html#re.M Commented Feb 12, 2021 at 6:25

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.