首页 > 解决方案 > Python中的正则表达式返回文本文件中的完整字符

问题描述

我想使用 python RegEx 搜索文本文件。但不是只返回我的搜索字符串,而是应该返回它匹配的整个字符串

python 3.7

   with open('movies.txt', 'w') as csv_file:
        csv_writer = writer(csv_file)
        headers = ['Title',  'Link']
        csv_writer.writerow(headers)

        for post in posts:
            title = post.find('p').get_text()
            link = post.find('a')['href']
            csv_writer.writerow([title, link])

    with open('movies.txt') as m1, open('movies.csv', 'w') as m2:
        for line in m1:
            movies = re.findall('th+', line)
            m1.writelines(movie + '\n' for movie in movies)

如果文本文件中的文本是:**你是什么势不可挡?unstoppable ** 我搜索了“unst”,它应该完整返回“unstopable”和“ unstoppable

如果匹配,它应该返回整个字符串,而不是只返回我的搜索字符串

标签: pythonregex

解决方案


假设您只想匹配字母数字字符,只需附加[a-zA-Z0-9]*到您的模式:

代码

import re

re.findall('unst[a-zA-Z0-9]*', 'What are you unstopable? unstoppable')

输出

在此处输入图像描述

希望这可以帮助。请让我知道是否出了问题。


推荐阅读