python通过多个分隔符和/或多个分隔符的组合拆分字符串

2024-03-29 00:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

输入:

x = "121, 1238,\nxyz,\n 123abc \n\rabc123"

我想用分隔符",", "\n", "\r", "\s"分割这个字符串以获得输出

['121', '1238', 'xyz', '123abc', 'abc123']

无论我尝试什么,分隔符都被接受为单个字符,而不是字符的组合。 e、 g

一,

re.split("\n|,|\s|\r", x)

输出

['121', '', '1238', '', 'xyz', '', '', '123abc', '', '', 'abc123']

  1. re.split("\n\s|,|\s|\r", x)

输出

['121', '', '1238', '', 'xyz', '', '123abc', '', 'abc123']

第二个比第一个稍有改进。但如果这是必需的,我需要手动给出所有可能的组合。
类似(具有更多组合):

re.split("\n\s|\s\n|\s\n\s|\n|,\s|\s,|\s,\s|,|\s|\r", x)

输出:

['121', '1238', 'xyz', '', '123abc', '', 'abc123']

有没有更好的办法


Tags: 字符串re手动字符split分隔符xyz办法
3条回答

允许re.split将任何分隔字符的1个或多个重复作为分隔符:

>>> re.split("[,\s]+", x)
['121', '1238', 'xyz', '123abc', 'abc123']

(“*”、“+”和“?”限定符都是贪婪的,它们尽可能匹配。)

结合@Johnny Mopp@alfinkel24的评论:

re.split("[\s,]+",  x)

将根据需要拆分字符串以

['121', '1238', 'xyz', '123abc', 'abc123']

说明:

  • [...]任何字符
  • +前面字符的一个或多个重复
  • \s任何空白字符,包括"\n, \r, \t"

    官方文件:

\s
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
For 8-bit (bytes) patterns: Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].

相关问题 更多 >