Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有所有特定子字符串的Python正则表达式findall_Python_Regex_Python 2.7 - Fatal编程技术网

带有所有特定子字符串的Python正则表达式findall

带有所有特定子字符串的Python正则表达式findall,python,regex,python-2.7,Python,Regex,Python 2.7,我正在尝试获取以下匹配正则表达式的输出,如下所示 所有扇区,例如[扇区34,诺伊达”,“Sec 434 Gurgaon”,“sec100'] p.S-sec47\n古尔冈是特例 但我怀疑输出是非常奇怪的[,'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 on

我正在尝试获取以下匹配正则表达式的输出,如下所示

所有扇区,例如[扇区34,诺伊达”,“Sec 434 Gurgaon”,“sec100']

p.S-sec47\n古尔冈是特例

但我怀疑输出是非常奇怪的[,'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

提前谢谢

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

>>> 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']
注:

在这里,我使用了\W none-word字符来匹配第一个匹配中的字符。如果您认为其他非单词字符正在书写,则应将其更改为

我们有两个选择:

?:[sS]ec::tor:-|\s+?\d+\W?\s+[A-Z][A-Z]+ [sS]ec?:tor?\d+

正如你所看到的,在第二部分中,我没有考虑一个字后面的扇区和数字,如果你认为可能有一个字之后,你可以添加::[s+[aZ] [aZ] +?在那之后

你可以选择:

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']

否则,请提供其他信息/扇区。

您确定需要sec100而不是sec100吗?@WiktorStribiżew。谢谢回复!是的,我想要sec100我的意思是,你怎么知道什么时候在数字后匹配单词字符,什么时候不匹配?Sec 434 Gurgaon和sec100之间的规则差异是什么?没有空间?要明白我的意思-。好吧,试试看@WiktorStribiżew Yaa。我得到了它。谢谢在一组中有两个可在字符串中的同一位置匹配的选项不是最佳做法。@WiktorStribiżew您的意思是?:\s+[a-Z][a-Z]+?或者什么?我是说这两种选择都是从同一个模式开始的。请参阅我的答案,以了解一种收缩的方法-只需确保公共部分在替换组之外。@WiktorStribiżew正如我在回答中所述,我之所以将它们分开,是因为还有另一个词具有不同的条件。例如,在第二个选项中,我们可能有类似sec100 Noida的单词。奇怪的是,我刚刚检查过,您的解决方案确实提取了sec100-