You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按分隔符分割字符串并忽略特定|0|567|模式?

解决方案

方法1:直接匹配目标内容(推荐)

不用纠结分割逻辑,直接用正则提取所有需要保留的字段——也就是排除掉0和567这两个固定值:

import re

line = "ABC | 0 | 567 | my name is | however"
# 匹配所有非|分隔的内容,且排除" 0 "和" 567 "
result = [item.strip() for item in re.findall(r'(?:\|)?\s*(?!0\s*\||567\s*\|)([^|]+)', line) if item.strip()]
print(result)
# 输出: ['ABC', 'my name is', 'however']

思路:(?!0\s*\||567\s*\|)是负向预查,确保当前匹配的内容不是0或567(后面跟着|),提取后用strip()清理字段前后的空格,过滤掉空内容。

方法2:替换特定模式后再分割

先把固定的| 0 | 567 |替换成单个|,再按|分割,相当于直接跳过这两个字段:

import re

line = "TQD | 0 | 567 | my name is | but"
# 替换目标模式后再分割
processed_line = re.sub(r'\| 0 \| 567 \|', '|', line)
result = [item.strip() for item in processed_line.split('|') if item.strip()]
print(result)
# 输出: ['TQD', 'my name is', 'but']

思路:针对你要忽略的固定模式| 0 | 567 |,直接替换成单个分隔符,分割逻辑就回到了常规的按|拆分,处理起来更直观。

方法3:改进分割正则

你原正则的负向预查位置错误,可以把| 0 | 567 |当作一个整体分隔符,同时保留普通|作为分隔符:

import re

line = "GED | 0 | 567 | my name is | haha"
pattern = re.compile(r'\| 0 \| 567 \||\|')
result = [item.strip() for item in pattern.split(line) if item.strip()]
print(result)
# 输出: ['GED', 'my name is', 'haha']

思路:正则匹配两种分隔符——要么是完整的| 0 | 567 |,要么是单个|,分割后清理空格并过滤空内容即可。


内容的提问来源于stack exchange,提问作者turtle_in_mind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:20:39