Python。从文件中提取字符串

标签 python regex

我有一个与此类似的文件:

RANDOMTEXTSAMPLE*
$SAMPLERANDOMTEXT
RANDOMSAMPLE*TEXT

我正在尝试提取末尾带有 * 的“sample”的所有实例并将其放入列表中。

我尝试过这样的事情:

import re

with open('file1.txt') as myfile:
content = myfile.read()

text = re.search(r'[0-9A-Z]{7}\*', content)
with open("file2.txt", "w") as myfile2:
myfile2.write(text)

但是我只会得到它找到的第一个结果。

任何有关如何获取列表中以 * 结尾的所有示例实例而不将 * 添加到列表的建议将不胜感激。

谢谢

编辑:小修正

最佳答案

你可以试试这个:

import re

samples = []

with open('file1.txt') as myfile:
    for line in myfile.readlines():
        if re.search(r'[0-9A-Z]{6}\*', line):                
            samples.append(line)

# print('SAMPLES: ', samples)

with open("file2.txt", "w") as myfile2:
    for s in samples:
        myfile2.write(s)

关于Python。从文件中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44713843/

相关文章:

python - Tm1 到 python 到 R

python - Buildozer 无法在 arm64/aarch64 CPU 上编译 libffi

python - 在Python中将列表映射到列表

python - python 的 random.Random.seed 是如何工作的?

java - PHP 在 Java 中的 `preg_match_all` 功能

regex - Google Analytics 本地 IP 过滤器不起作用

python - 如何在 django 登录页面中添加 otp 身份验证

java - 对于相同输入,使用相同正则表达式的字符串数组长度存在差异

c - 首先获取一个带空格的字符串,然后在制表符之后获取另一个字符串

python : replacing a space after numbers keeping space after letters