想在不同字符之间添加一个空格。我现在将它添加到每个字符之间,而如果字符相同(连续),我想省略它。
import re
string = "CEEEETTEEEEGGGCCBCTTBHHHHHCCEEEEEEEEETTEETT"
space = re.compile(r"(?<!^)(?=[CEHBGITS])(?!$)")
print(space.sub("\1", string))
预期结果是:C EEEE TT EEEE GGG CC B C TT B HHHHH CC EEEEEEEEE TT EE TT
最佳答案
你可以使用
re.sub(r'(?<=(.))(?!\1)(?=.)', ' ', str)
Python demo <-\(ツ)/-> Regex demo
正则表达式包含以下元素。
(?<=(.)) # positive lookbehind asserts that the current string location
# is preceded by a character that is saved to capture group 1
(?!\1) # negative lookahead asserts that the current string
# location is not followed by the content of capture group 1
(?=.) # positive lookahead asserts that current string location
# is followed by a character
当前字符串位置可以认为是连续字符之间的位置。
关于python - 用于在不同字符后插入空格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71135131/