【发布时间】:2018-10-09 06:17:46
【问题描述】:
我有一个模式,例如 word-\nword,即单词是连字符并用换行符分隔的。
我希望输出为 word-word。我用下面的代码得到 word-\nword。
text_string = "word-\nword"
result=re.findall("[A-Za-z]+-\n[A-Za-z]+", text_string)
print(result)
我试过了,但没有成功,我没有得到任何结果。
text_string = "word-\nword"
result=re.findall("[A-Za-z]+-(?=\n)[A-Za-z]+", text_string)
print(result)
我怎样才能做到这一点。 谢谢!
编辑:
替换并运行一个简单的正则表达式是否有效
text_string = "aaa bbb ccc-\nddd eee fff"
replaced_text = text_string.replace('-\n', '-')
result = re.findall("\w+-\w+",replaced_text)
print(result)
或使用CertainPerformance建议的方法
text_string = "word-\nword"
result=re.sub("(?i)(\w+)-\n(\w+)", r'\1-\2', text_string)
print(result)
【问题讨论】:
标签: regex python-3.x regex-lookarounds