【问题标题】:How to split using mutli-character delimiters in Python?如何在 Python 中使用多字符分隔符进行拆分?
【发布时间】:2018-06-08 13:36:15
【问题描述】:

我有一个字符串:

string = 'i-phone is popular - many people like it (user-friendly system, fast, good support)'

如何使用正则表达式将其拆分为:

split_string = ['i-phone', 'is', 'popular', 'many', 'people', 'like',  'it', 'user-friendly', 'system', 'fast', 'good', 'support']

问题是- 包含 2 个空格和 1 个连字符。

我试过了: split_string = re.split('[() - ]', 字符串) 但我得到了:

['i-phone', 'is', 'popular', '-', 'many', 'people', 'like', 'it', '', 'user-friendly', 'system,', 'fast,', 'good', 'support', '']

谢谢。

【问题讨论】:

  • 希望它是 [stackoverflow.com/questions/3939361/… 的副本
  • 谢谢,瑜伽士。但我做不到。能给我看看么?谢谢。
  • 可能类似于\s+(?:[()-]\s*)?|[,()]\s*
  • @John 你“做不到”是什么意思? SO 不是“为我工作”服务。它的存在是为了帮助您填写缺少的知识,并且您可以准确地确定您缺少哪些知识,尤其是在您获得资源调查之后。跨度>
  • 古尔曼,谢谢。得到的列表是['i-phone', 'is', 'popular', 'many', 'people', 'like', 'it', 'user-friendly', 'system', 'fast', 'good', 'support', '']

标签: python regex


【解决方案1】:

试试这个正则表达式来拆分:

\s+(?:[()-]\s*)?|[,()]\s*

Click for Demo

说明

  • \s+ - 匹配 1+ 个空格
  • (?:[()-]\s*)? - 匹配 ()-,后跟 0+ 个空格。末尾的 ? 使此子部分可选
  • | - 或
  • [,()]\s* - 匹配 ,() 后跟 0+ 个空格

【讨论】:

  • 古尔曼,它有效。非常感谢您的回答和解释。
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多