这是一个完整的答案,展示了如何使用 replace() 来完成它。
strings = ['(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)']
results = []
target_word = 'message'
separators = ['(static string)', '(different static string )', '(last static string)']
for s in strings:
for sep in separators:
s = s.replace(sep, '')
name, message = s.split()
if target_word in message:
results.append((name, message))
>>> results
[('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message')]
请注意,这将匹配任何包含子字符串 target_word 的 message。它不会寻找单词边界,例如将此运行与target_word = 'message' 与target_word = 'sag' 进行比较 - 将产生相同的结果。如果您的单词匹配更复杂,您可能需要正则表达式。