【发布时间】:2017-12-12 03:56:52
【问题描述】:
我正在尝试检查一个字符串,如果它存在,我不想写入文件,但字符串在它们之间的不同位置有空格,这使得它难以捕获。
示例文本:
this is test (enclosed ("further enclosed...
Line to be printed:1
this is test(enclosed ("further enclosed...
Line to be interpreted
this is test(enclosed("further enclosed...
this is test (enclosed("further enclosed...
预期输出
Line to be printed:1
Line to be printed:2
我尝试了下面的代码,但它不起作用:
for word in words:
if 'this is test .*(enclosed .*(\"' not in word :
fw.write (word)
我正在将它写入文件。
有人可以帮助我如何实现预期的输出吗?如果您需要更多详细信息,请告诉我。另外,我不想使用类似
的内容if 'this is test (enclosed (\"' not in word or 'this is test(enclosed(\"' not in word :
【问题讨论】:
-
和
not in不会查找正则表达式。您必须明确使用正则表达式包。 -
解决问题的两种方法:1)在模式中的任何地方放置可选空格(Neos07 方法)或 2)在使用更简单的模式(使用
re.match)。我让你选择最合适的方法。 -
@CasimiretHippolyte 并使用正则表达式包 :)
-
是的:使用
re.search而不是in。导入re不会将子字符串搜索转换为正则表达式搜索。 -
@Saurabh:
import语句不会向语言添加功能,但会从导入的模块中提供可用的方法。查看 re 模块手册页,了解哪些新方法可用以及如何使用它们。
标签: python regex removing-whitespace