Skip to main content
 首页 » 编程设计

python之如何在 '/' 分隔符上拆分字符串,但在 '/' 紧接在 '\' 之后时防止拆分

2025年05月04日30EasonJim

我正在尝试使用由“/”字符分隔的 Python 拆分字符串数据。问题是字符串可能多次出现 '/' 字符,但我只想使用 '/' 而不使用 '\/' 拆分它

例如,我试图将字符串 '1\/2/CD' 拆分为 '1\/2' 和 'CD'

请您参考如下方法:

在正则表达式中使用否定的回顾断言:

>>> re.split(r'(?<!\\)/', r'1\/2/CD') 
['1\\/2', 'CD'] 

来自docs :

(?<!...) 

Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

当第一个切片为空时,这会起作用:

>>> re.split(r'(?<!\\)/', r'/CD') 
['', 'CD']