python - 基于特定模式和编辑字符串的拆分

标签 python regex split pattern-matching

我正在尝试根据特定模式拆分字符串,以便稍后在添加几个字符后重新加入它。

这是我的字符串示例:“123\babc\b:123”,我需要将其转换为“123\babc\\"b\":123”。我需要在很长的字符串中多次执行此操作。我尝试了以下变体:

regex = r"(\\b[a-zA-Z]+)\\b:"
test_str = "123\\babc\\b:123"
x = re.split(regex, test_str)

但它并没有在我加入的正确位置 split 。有没有另一种方法/另一种 split 和加入的方法?

最佳答案

你是对的,你可以按照建议使用 re.split 来完成。您可以按 \b 拆分,然后使用特定分隔符重建输出(并在需要时保留 \b)。

举个例子:

# Import module
import re

string = "123\\babc\\b:123"

# Split by "\n"
list_sliced = re.split(r'\\b', "123\\babc\\b:123")
print(list_sliced)
# ['123', 'abc', ':123']

# Define your custom separator
custom_sep = '\\\\"b\\"'
# Build your new output
output = list_sliced[0]
# Iterate over each word
for i, word in enumerate(list_sliced[1:]):
    # Chose the separator according the parity (since we don't want to change the first "\b")
    sep = "\\\\b"
    if i % 2 ==  1:
        sep = custom_sep
    # Update output
    output += sep + word

print(output)
# 123\\babc\\"b\":123

关于python - 基于特定模式和编辑字符串的拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029044/

相关文章:

php - 将 UTF-8 字符存储在 ANSI 文件中 [PHP][REGEX]

java - 匹配出现在特定模式之后的字符串

java - 使用 split 或 tokenizer 将字符串放入大括号内的方法

python - matplotlib 未在条形图的 x 轴上显示第一个标签

python - 无法从网页的某些脚本标记中获取电子邮件链接

python - 正则表达式排除破折号和下划线作为最后一个字符

regex - 如何使用Excel VBA脚本删除某些字符

javascript - 使用 split/join 将字符串替换为数组

python - 使用 wxPython 用鼠标画一条连续的线

python - 查找两个 numpy 数组之间的索引映射