正则表达式去除位信号噪声尖峰

joa*_*000 5 python regex

我正在处理有时会产生噪音尖峰的射频信号.
输入是这样的:
00000001111100011110001111100001110000001000001111000000111001111000

在解析信号中的数据之前,我需要删除尖峰位,即0和1的序列,其长度低于(在本例中)3.

所以基本上我需要匹配匹配0000000111110001111000111110000111000000(1)000001111000000111(00)1111000
后,我将它替换为之前的位,所以一个干净的信号看起来像这样: 00000001111100011110001111100001110000000000001111000000111111111000

到目前为止,我用两个不同的正则表达式实现了这个目

self.re_one_spikes = re.compile("(?:[^1])(?P<spike>1{1,%d})(?=[^1])" % (self._SHORTEST_BIT_LEN - 1))
self.re_zero_spikes = re.compile("(?:[^0])(?P<spike>0{1,%d})(?=[^0])" % (self._SHORTEST_BIT_LEN - 1))
Run Code Online (Sandbox Code Playgroud)

然后我迭代匹配并替换.

如何使用单个正则表达式执行此操作?我可以使用正则表达式来替换不同大小的匹配吗?
我试过这样的事情没有成功:

re.compile("(?![\1])([01]{1,2})(?![\1])")
Run Code Online (Sandbox Code Playgroud)

Jor*_*ley 6

import re
THRESHOLD=3

def fixer(match):
    ones = match.group(0)
    if len(ones) < THRESHOLD: return "0"*len(ones)
    return ones

my_string = '00000001111100011110001111100001110000001000001111000000111001111000'
print(re.sub("(1+)",fixer,my_string))
Run Code Online (Sandbox Code Playgroud)

如果你想删除零的"尖峰"

def fixer(match):
    items = match.group(0)
    if len(items) < THRESHOLD: return "10"[int(items[0])]*len(items)
    return items

print(re.sub("(1+)|(0+)",fixer,my_string))
Run Code Online (Sandbox Code Playgroud)