【发布时间】:2020-08-04 12:56:06
【问题描述】:
我正在尝试删除方括号内字符周围的空格,如果下一个标记是非空白字符,则在方括号外只留下 1 个空格。例如,banana [ pasta pause] [12 haha] [author bird] tree [red] abc [blue] 将是banana[pastapause][12haha][authorbird] tree[red] abc[blue]
是否有尾随/前导空格或空格左/右的位置都没有关系。到目前为止,我得到了正方形的空间。这是我删除内部空格的代码:
cleaned_texts = []
p = re.compile("\[(\s*?.*?\s*?)\]")
matches = p.findall(orig_text)
for match in matches:
cleaned = re.sub("\s","",match)
cleaned_texts.append(cleaned)
text = orig_text
for i in range(len(matches)):
cleaned = re.sub(matches[i],cleaned_texts[i],text)
text = cleaned
如果它是w[]w 的形式,在外面添加一个空格,w 是一个非空格字符,我得到了一个非常难看的版本,它仍然有一些极端情况。我不确定如何有效地做到这一点。
#find 2 spaces or leading and trailing space
p = re.compile("\s(\[.*?\])\s|\s(\[.*?\])$|^\s?(\[.*?\])\s?")
temp = p.sub(r"\1"," "+cleaned)
#find [] with form a[]b and add a space
p = re.compile("(\S)(\[.*?\])(\S)")
temp_2 = p.sub(r"\1\2"+" "+r"\3",temp)
#find 2 spaces or leading and trailing space one more time
p = re.compile("\s(\[[a-zA-Z-0-9]*?\])\s|^\s?(\[[a-zA-Z-0-9]*?\])\s|\s(\[[a-zA-Z-0-9]*?\])\s?$")
temp_3 = p.sub(" "+r"\1",temp_2)
【问题讨论】:
-
如果你有
[inside] out side [inside]怎么办? -
@rici 应该是
[inside]out side[inside]