【问题标题】:Python RegEx clean-up randomly placed new linesPython RegEx 清理随机放置的新行
【发布时间】:2017-12-05 14:48:36
【问题描述】:

我收到以下文本并希望对新行进行一些正则表达式清理

Quality risk management. A systematic process for the assessment, control,
communication and review of risks to quality across the lifecycle. (ICH Q9)

Simulated agents. A material that closely approximates the physical and, where
practical, the chemical characteristics, e.g. viscosity, particle size, pH etc., of the product
under validation.

State of control. A condition in which the set of controls consistently provides assurance
of acceptable process performance and product quality.

Traditional approach. A product development approach where set points and operating
ranges for process parameters are defined to ensure reproducibility.

Worst Case. A condition or set of conditions encompassing upper and lower processing
limits and circumstances, within standard operating procedures, which pose the greatest
chance of product or process failure when compared to ideal conditions. Such conditions
do not necessarily induce product or process failure.


User requirements Specification (URS). The set of owner, user and engineering
requirements necessary and sufficient to create a feasible design meeting the intended
purpose of the system.

这几乎可以工作: re.sub(r'\w(?

但它也会删除最后一个和第一个字符...我该如何避免这种情况?

这是 regex101 上的相同示例:

https://regex101.com/r/5uEsJR/1

【问题讨论】:

  • here一样的问题吗?
  • 你可以在你的正则表达式中使用lookahead和lookbehind作为re.sub(r'(?<=\w)\n(?=\w)', ' ')
  • 是的,但他确实回答了我的问题(为什么我将其标记为已解决) - 我问错了

标签: python regex python-2.7


【解决方案1】:

由于您的reges 在\n 之前和之后都匹配\w,并且没有被放回替换,所以它会丢失。

您可以将环视用作:

re.sub(r'(?<=\w)\n(?=\w)', ' ')

RegEx Demo

  • (?&lt;=\w): 断言我们之前有一个单词字符
  • \n: 匹配换行符
  • (?=\w): 断言我们下一个单词字符

【讨论】:

  • 它在 regex101 上完美运行(非常感谢)。但我无法弄清楚我在这里做错了什么repl.it/@Norfeldt/SuperficialCumbersomeTenrec - 是我缺少的g 标签吗??
  • 这段代码没有什么特别之处。它也适用于 repl.it。只需创建一个新的代码示例并从我的 complete ideone 代码链接粘贴完整的代码。
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2016-12-29
  • 2018-01-05
  • 2020-07-08
  • 2020-09-15
  • 2023-03-20
相关资源
最近更新 更多