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

如何用变量指定的多个正则模式调用Python re.split拆分字符串

使用多个变量作为正则表达式拆分字符串的解决方法

要同时用两个变量作为拆分模式,你需要把变量的值拼接成符合正则语法的字符串,而不是直接用|连接变量名或者把变量名写进原始字符串里。

正确写法示例

方法1:字符串拼接(f-string或普通拼接)

import re

string_to_split = "This_is_the_string_to_split"
pattern1 = "_is_"
pattern2 = "_to_"

# 用f-string拼接模式
result = re.split(f"{pattern1}|{pattern2}", string_to_split)
print(result)  # ['This', 'the_string', 'split']

# 或者普通字符串拼接
result = re.split(pattern1 + "|" + pattern2, string_to_split)
print(result)  # ['This', 'the_string', 'split']

方法2:预编译正则表达式

如果需要重复使用这个模式,预编译会更高效:

import re

string_to_split = "This_is_the_string_to_split"
pattern1 = "_is_"
pattern2 = "_to_"

combined_pattern = re.compile(f"{pattern1}|{pattern2}")
result = re.split(combined_pattern, string_to_split)
print(result)  # ['This', 'the_string', 'split']

为什么之前的写法失败?

  • re.split(pattern1|pattern2, string_to_split):Python中字符串类型不支持|运算符,这是正则语法里的"或",但不能直接用在两个字符串变量之间,所以抛出TypeError。
  • re.split(r'pattern1|pattern2', string_to_split):这里的字符串是字面量pattern1|pattern2,正则引擎会尝试匹配字符串里的"pattern1"或"pattern2",而不是变量pattern1和pattern2的值,所以匹配不到任何内容,返回原字符串。

注意事项

如果你的模式变量里包含正则特殊字符(比如.、*、+等),需要先用re.escape()转义,避免这些字符被当成正则语法解析:

import re

pattern_with_special = "a.b"
escaped_pattern = re.escape(pattern_with_special)
# 此时escaped_pattern是"a\.b",会匹配字面量的a.b而不是a任意字符b

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:37:46