我正在尝试使用正则表达式和我的文本文件编写代码。我的文件逐行包含以下单词:
each
expressions
flags
in
from
given
line
of
once
lines
no
我的目的是:显示通过从给定子字符串中删除字母而创建的单词。
例如,如果我的子字符串是"flamingoes"
,我的输出应该是;
flags
in
line
lines
no
因为它们是通过删除字母从我的子字符串中创建的,并且它们也在我的文本文件中。
我做了很多关于正则表达式的工作,但我对这个挑战很感兴趣。有什么正则表达式解决方案可以解决这个问题吗?
发布于 2019-06-02 19:21:52
您应该为要查找的每个单词创建正则表达式。每个字母之间的表达式.*?
是一个非贪婪模式,这将避免回溯(至少部分回溯),并使搜索速度更快。
例如,单词“给定”的正则表达式将为g.*?i.*?v.*?e.*?n
。
import re
def hidden_words(needles, haystack):
for needle in needles:
regex = re.compile(('.*?').join(list(needle)))
if regex.search(haystack):
yield needle
needles = ['each', 'expressions', 'flags', 'in', 'from',
'given', 'line', 'of', 'once', 'lines', 'no']
print(*hidden_words(needles, 'flamingoes'), sep='\n')
发布于 2019-06-02 19:30:06
基本上每个字符都是可选的。一个简单的
import re
word = 'flamingoes'
pattern = ''.join( c+'?' for c in word ) # ? Marks the letter as optional
for line in open('file').readLines():
line = line.strip()
m = re.match(pattern, line)
if m:
print(line)
应该足够了
https://stackoverflow.com/questions/56414347
复制相似问题