【问题标题】:Splitting list item into two items in place with regex使用正则表达式将列表项拆分为两个项目
【发布时间】:2012-01-21 13:02:27
【问题描述】:

所以我输入了一个包含如下元素的列表:

"2008 年历年建筑重建重铺 & 修复街道和道路”

我正在遍历列表。对于每次迭代,首先我想验证模式 INTspacespacefor 是否在字符串中,我知道我可以这样做:

re.search('\\d+\s\sfor',string)

一旦我确认其中一个元素匹配,我想在 INT 和“for”之间将该元素拆分为两个元素。有没有简单的方法可以做到这一点?

因此,此示例输出将是:

[item1,item2,...item10,"calendar year 2008","for construction reconstruction resurfacing & repair of streets & roads",item11,item12...]

【问题讨论】:

  • OP 使用双空格编写了示例短语,但格式化工具取消了它们。

标签: python regex list split element


【解决方案1】:

你可以使用向后看和向前看

re.split('(?<=\d)\s\s(?=for)',string)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 2020-08-25
  • 2020-08-07
  • 2017-09-12
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多