python - 在正则表达式匹配之间插入空格

标签 python regex

我想通过使用正则表达式查找字符串中的拼写错误并在匹配的表达式之间插入空格字符来取消连接它们。

我尝试了类似问题的解决方案...但它对我不起作用 -( Insert space between characters regex );解决方案-在 re.sub 中使用替换字符串作为 '\1\2' 。

import re

corpus = ''' 
This is my corpus1a.I am looking to convert it into a 2corpus 2b.
'''

clean = re.compile('\.[^(\d,\s)]')
corpus = re.sub(clean,' ', corpus)

clean2 = re.compile('\d+[^(\d,\s,\.)]')
corpus = re.sub(clean2,'\1 \2', corpus)

预期输出:

This is my corpus 1 a. I am looking to convert it into a 2 corpus 2 b.

最佳答案

您需要将捕获组括号放在与要复制到结果的每个字符串相匹配的模式周围。

也无需在 \d 之后使用 +。您只需匹配号码的最后一位数字即可。

clean = re.compile(r'(\d)([^\d,\s])')
corpus = re.sub(clean, r'\1 \2', corpus)

DEMO

关于python - 在正则表达式匹配之间插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944944/

相关文章:

python - 如何在django中定义两个数据库,一个用于生产,一个用于开发

regex - C#正则表达式匹配方括号

regex - Emacs:如何复制正则表达式匹配?

regex - 使用 Regexextract 从 Google 表格中的文本中提取日、月、2 位数字年份

具有随机属性的对象的Python列表

python - 使用 Python 教程进行测试驱动开发 : Error trying to open Firefox with Selenium on MacOSX

python - 相同高度的 Tkinter 列表框和复选框

Python: NameError 名称 '[input]' 未定义

jquery - 简单的正则表达式在 jQuery 中提取方括号之间的内容

javascript - 匹配字符集但否定序列的正则表达式