【问题标题】:Python regex findall with all specific substrings具有所有特定子字符串的 Python 正则表达式 findall
【发布时间】:2016-08-30 11:35:38
【问题描述】:

我正在尝试将以下匹配正则表达式的输出作为

所有部门,例如。 ['Sector-34, Noida', 'Sec 434 Gurgaon', 'sec100']

P.S - sec47,\n gurgaon 是特例

但我怀疑输出很奇怪,因为 [('', 'tor')]

import re

string = "Sector-34, Noida is found to be awesome place I went to eat burgers there and Sec 434 Gurgoan is also good sec100 is one the finest places for outing."

match =  re.findall(r"Sec(tor)?-?\d+\s+?\w+|Sec(tor)?\s+?\d+", string, re.IGNORECASE)

print match

谢谢,提前!

【问题讨论】:

  • 您确定需要sec100 而不是sec100 is
  • @WiktorStribiżew。感谢回复!是的,我也想要 sec100
  • 我的意思是,你怎么知道什么时候匹配数字后面的单词字符,什么时候不匹配? Sec 434 Gurgaonsec100 之间的规则区别是什么?没有空间?看看我的意思 - Sec(?:tor)?-?\s*\d+\W+?\w+.
  • @WiktorStribiżew Yaa。我知道了。谢谢!

标签: python regex python-2.7


【解决方案1】:

这是一种可以提供预期输出的方法,但不是通用方法(因为您没有向我们提供一般条件):

>>> re.findall(r'(?:[sS]ec(?:tor)?(?:-|\s+)?\d+\W?\s+[A-Z][a-z]+)|[sS]ec(?:tor)?\d+', string)
['Sector-34, Noida', 'Sec 434 Gurgoan', 'sec100']

注意事项:

  1. 这里我使用\W(无单词字符)来匹配,等字符在第一次匹配中。如果您认为其他无字字符有问题,则应将其更改为 ,

  2. 这里有两个选择:

    1. (?:[sS]ec(?:tor)?(?:-|\s+)?\d+\W?\s+[A-Z][a-z]+)
    2. [sS]ec(?:tor)?\d+

正如您在第二部分中看到的,我没有考虑扇区和数字之后的单词,如果您认为后面可能有单词,您可以在其后添加(?:\s+[A-Z][a-z]+)?

【讨论】:

  • 在一个组中有两个备选方案可以在字符串中的相同位置匹配不是最佳做法。
  • @WiktorStribiżew 你的意思是(?:\s+[A-Z][a-z]+)? 还是什么?
  • 我的意思是这两种选择以相同的模式开始。请参阅我的答案以了解一种合同方式 - 只需确保公共部分在 交替组之外。
  • @WiktorStribiżew 正如我在回答中所描述的,我将它们分开的原因是因为还有另一个词具有不同的条件。例如,对于第二个选项,我们可能在之后有类似 sec100 Noida 的词。
  • 奇怪,我刚刚检查过,您的解决方案确实提取了sec100 is - ideone.com/iYIrUG
【解决方案2】:

你可以去:

import re

rx = re.compile(r'(\b[Ss]ec(?:tor)?[- ]?\d+\b[,\s]*\b\w+\b)')

string = """
Sector-34, Noida is found to be awesome place I went to eat burgers there and Sec 434 Gurgoan is also good sec47, 
gurgaon is one the finest places for outing.
"""

sectors = [match.group(1).replace("\n", "") \
            for match in rx.finditer(string)]
print(sectors)
# ['Sector-34, Noida', 'Sec 434 Gurgoan', 'sec47, gurgaon']

否则,请提供其他信息/部门。

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2018-07-20
    • 2022-11-16
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多