gpt4 book ai didi

python - 在Python中使用正则表达式分隔符分割字符串

转载 作者:行者123 更新时间:2023-12-01 01:14:35 26 4
gpt4 key购买 nike

我有以下字符串:

txt='agadsfa_(2asdf_sdfsaf)asfsadf[adsf_klnalfk;jn234kmafs)adfs,nlnawr23'

这是分隔符:

delimiters = " \t,;.?!-:@[](){}_*/"

作为输出,我想要这个值列表:

"agadsfa","2asdf","sdfsaf","asfsadf","adsf","klnalfk","jn234kmafs","adfs","nlnawr23"

我尝试使用正则表达式:

re.split(delimiters,txt)

但我收到此错误:

re.error: unterminated character set at position 10

这里出了什么问题?

最佳答案

您的正则表达式不正确。从注释中,您添加了不得触及 delimiters 字符串的要求。

然后我们需要做的是处理输入字符串并将其转换为可供 split() 使用的正确正则表达式。方法如下:

# need to enclose regex in [], we want to split on any of
# the chars; also some of the chars need to be escaped
delimiters = ' \t,;.?!-:@[](){}_*/'
regex = delimiters.replace(']', '\]').replace('-', '\-')
regex = r'[{}]+'.format(regex)

结果符合预期:

txt = 'agadsfa_(2asdf_sdfsaf)asfsadf[adsf_klnalfk;jn234kmafs)adfs,nlnawr23'
re.split(regex, txt)
=> ['agadsfa', '2asdf', 'sdfsaf', 'asfsadf', 'adsf', 'klnalfk', 'jn234kmafs', 'adfs', 'nlnawr23']

关于python - 在Python中使用正则表达式分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com