在正则匹配之间插入空间



我想使用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

我不确定其他可能的输入,我们可能能够使用类似的表达式添加空格:

(d+)([a-z]+)b

之后,我们将用一个空间替换任意两个空间,但可能不确定:

import re
print(re.sub(r"s{2,}", " ", re.sub(r"(d+)([a-z]+)b", " \1 \2", "This is my corpus1a.I am looking to convert it into a 2corpus 2b")))

如果您想进一步探索或修改该演示的右上面板上的表达式,并且在此链接中,可以观察它如何匹配某些示例输入,如果需要的话。

以括号()为标志的捕获组应围绕您要匹配的模式。

所以这应该对您有用

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

REGEX (d+)([^d,s])读取:匹配1或更多数字(d+(作为第1组(第一组括号(,匹配非数字和非Whitespace作为第2组。

您不起作用的原因是您没有围绕要重复使用的模式的括号。

最新更新