【问题标题】:Split a string and keep the delimiters as part of the split string chunks, not as separate list elements拆分字符串并将分隔符保留为拆分字符串块的一部分,而不是单独的列表元素
【发布时间】:2020-10-16 21:15:09
【问题描述】:

这是In Python, how do I split a string and keep the separators?的衍生产品

rawByteString = b'\\!\x00\x00\x00\x00\x00\x00\\!\x00\x00\x00\x00\x00\x00'

如何使用 "\\!" 将此 rawByteString 拆分为多个部分作为分隔符而不删除分隔符,所以我得到:

[b'\\!\x00\x00\x00\x00\x00\x00', b'\\!\x00\x00\x00\x00\x00\x00']

我不想使用[b'\\!' + x for x in rawByteString.split(b'\\!')][1:],因为那会使用 string.split() 并且只是一种解决方法,这就是为什么这个问题被标记为“re”模块的原因。

【问题讨论】:

  • @WiktorStribiżew import re rawByteString = b'\\!\x00\x00\x00\x00\x00\x00\\!\x00\x00\x00\x00\x00\x00' [x for x in re.split(b'(\\\\!)', rawByteString)][1:]: [b'\\!', b'\x00\x00\x00\x00\x00\x00', b'\\!', b'\x00\x00\x00\x00\x00\x00'] 这不是我需要的,我需要[b'\\!\x00\x00\x00\x00\x00\x00', b'\\!\x00\x00\x00\x00\x00\x00']
  • re.split(rb'(?!\A)(?=\\!)', rawByteString),见ideone.com/L9n1V9
  • 看看lst_Bytes = re.split(b'(?<!^)(?=\\\\!)', rawByteString)是否适合你
  • @JvdV 和 Lorenz 模式相同,因为 (?!\A) = (?<!^) 因为没有通过 re.M 并且 "\\\\" = r"\\"
  • 我修改了标题,以便显示与其他问题的区别。

标签: python regex split re rawbytestring


【解决方案1】:

你可以使用

re.split(rb'(?!\A)(?=\\!)', rawByteString)
re.split(rb'(?!^)(?=\\!)', rawByteString)

查看sample regex demo(字符串输入已更改,因为空字节不能是字符串的一部分)。

正则表达式详细信息

  • (?!^) / (?!\A) / (?<!^) - 不是字符串开头的位置
  • (?=\\!) - 不紧跟反斜杠的位置 + !

注意事项

  • 由于使用字节字符串,所以在定义模式字符串字面量时需要b 前缀
  • r 使字符串文字成为原始字符串文字,这样我们就不必使用双转义反斜杠,并且可以使用 \\ 来匹配字符串中的单个 \

Python demo:

import re
rawByteString = b'\\!\x00\x00\x00\x00\x00\x00\\!\x00\x00\x00\x00\x00\x00'
print ( re.split(rb'(?!\A)(?=\\!)', rawByteString) )

输出:

[b'\\!\x00\x00\x00\x00\x00\x00', b'\\!\x00\x00\x00\x00\x00\x00']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-28
    • 2016-11-26
    • 2022-11-03
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多