Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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 - Fatal编程技术网

Python正则表达式findall

Python正则表达式findall,python,regex,Python,Regex,我正在尝试使用Python 2.7.2中的正则表达式从字符串中提取所有出现的带标签的单词。或者简单地说,我想提取[p][/p]标记中的每一段文本。 以下是我的尝试: regex = ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?" line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."

我正在尝试使用Python 2.7.2中的正则表达式从字符串中提取所有出现的带标签的单词。或者简单地说,我想提取
[p][/p]
标记中的每一段文本。 以下是我的尝试:

regex = ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(pattern, line)
印刷
person
产生
['President[p]'、[/p]'、[p]Bill Gates[/p]].

正确的正则表达式是什么:
['[p]巴拉克•奥巴马[/p]',[p]比尔•盖茨[/p]]
或者
['Barrack Obama','billgates']

import re
regex = ur"\[P\] (.+?) \[/P\]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(regex, line)
print(person)
屈服

['Barack Obama', 'Bill Gates']

regex
ur“[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?”
完全相同 unicode作为
u'[[1P].+?[/P]]+?'
除了更难阅读之外

第一个括号内的组
[[1P]
告诉您列表中的任何字符
['['[','1','p']]
都应该匹配,同样,第二个括号内的组
[/p]]
也应该匹配。这根本不是您想要的。因此

  • 拆下外部封闭方括号。(同时拆下 杂散的
    1
    P
    前面)
  • 要保护
    [P]
    中的文字括号,请使用 反斜杠:
    \[P\]
  • 若要仅返回标记内的单词,请将分组置于括号中 大约
    +?
试试这个:

   for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject):
        # match start: match.start()
        # match end (exclusive): match.end()
        # matched text: match.group()

你的问题不是100%清楚,但我假设你想找到标签中的每一段文字:

>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']

您可以将您的模式替换为

regex = ur"\[P\]([\w\s]+)\[\/P\]"
用这个模式,

pattern='\[p\].+?\[\/p\]'


检查

注意格式设置;使用预览区域。因为格式设置不正确,反斜杠被大量使用(降价很糟糕)。你为什么要做
[\w\s]+
而不是他使用的
*?
呢?在我看来,
*?
更可能是他想要的东西。
[\w\s]
的局限性是可怕的。故意的局限性。我使用[\w\s]+是因为询问者显然想要提取很少包含数字的名称。还要注意,询问者想要提取的是单词,而不是数字。不过,这只是我的意见,CMIIW关于带有口音等有趣特征的名称如何?
不是重新匹配('\w',ué'))
。如果名称是任意的,你不应该忽视非拉丁名称的可能性。我非常喜欢这个答案。如果你只想处理匹配项,那么这就可以了,而不需要任何额外的语句,如1)保存列表,2)处理列表并不等同于str='purplealice@google.com,胡说八道bob@abc.com废话洗碗机##此处re.findall()返回找到的所有电子邮件字符串的列表email=re.findall(r'[\w\.-]+@[\w\.-]+',str)##['alice@google.com', 'bob@abc.com“]对于电子邮件中的电子邮件:#对找到的每个电子邮件字符串执行一些操作打印电子邮件