我正在尝试根据特定模式拆分字符串,以便稍后在添加几个字符后重新加入它。
这是我的字符串示例:“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/