python - 用于在不同字符后插入空格的正则表达式

标签 python regex string

想在不同字符之间添加一个空格。我现在将它添加到每个字符之间,而如果字符相同(连续),我想省略它。

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/

相关文章:

c - 通过 strdup() 和 malloc() 构造字符串之间有什么实际区别吗?

python - 导入 STLdecompose 结果出错 - 无法从 '_maybe_get_pandas_wrapper_freq' 导入名称 'statsmodels.tsa.filters._utils'

python - 如何访问我之前保存在 IDLE 和/或 Jupyter 中的 .py 文件?

python - 在 Python 中使用正则表达式替换除特定元素之外的所有元素

java - 正则表达式从插入查询中提取值

ruby - 转义 TextMate 的 $DIALOG 命令的 Ruby 字符串

javascript - 如何使用 FastAPI 为跨源请求设置 cookie

regex - 匹配 Razor 之类表达式的正则表达式

swift - 如何在不丢失顺序的情况下删除 Swift 中字符串的重复行?

r - 字符串分解