我读了一个有以下文字的文件
this is::b(test file).
extra this is::another(test file).
this is::a(test file)
我能读这个文件并把它写在另一个文件中。我想在以后捕获这个单词
this is:: and before '(' i.e 'b' from the first line and 'a' from the 3rd line and store it in a list and nothing from the 2nd line since it has extra word before 'this is' I tried using the Regular expression:
for item in lines:
print(item)
fw.write(item)
found=None
found=(re.search('this is::(.+?)[)]',y).group(1)
其中y=从文件中读取的字符串
y=''.join(lines)
但它只捕获“b”,并在每行之后添加新行。你知道吗
有没有人能建议我应该如何去实现它。 需要的文件:
this is::b(test file).
An extra line:b
extra this is:another(test file).
this is::a(test file).
An extra line:a
我想这就是你想要的?你知道吗
[编辑:更新代码以反映问题的更改]
收益率
注意,我给出了一个正则表达式来表示最简单的情况;如果你需要一个更好的正则表达式,你应该自己独立地解决这个问题。这里有一个很好的工具debuggex,用于帮助测试正则表达式。你知道吗
干杯
用于捕获文本
例如,您可以搜索字符串文字
this is::
,然后创建一个子模式(.*?)
(the?使之不贪婪)。你知道吗示例
输出
用于在文件中追加行
我不清楚你想要什么,但如果你只是想附加到一个文件。。。见this post
示例
相关问题 更多 >
编程相关推荐