[英]How to search for a particular string with in a regex group with in a single regex in Python?
我想在正则表达式的最后一组中将“名词”一词与之匹配。
到目前为止,我有:
tags = 'motocykl mutka 1 motorcycle bike moped 0 transportation openair noun'
print re.search('(?P<pol>\D+)(?P<d1>\d)(?P<eng>\D+)(?P<d2>\d)(?P<end>\D+)', tags).group('end')
我所得到的只是最后一个字符串:
transportation openair noun
我只需要得到:
noun
更新:
我忘了提及“名词”不会出现在我要对其运行正则表达式的某些字符串中的最后一个单词上。 例如:
tags = 'dźwig 1 crane 0 noun construction vehicle'
tags = 'trycykl 1 tricycle 0 child noun transportation'
关于如何在单个正则表达式中执行此操作的任何想法?
不确定\\D+?
是什么意思\\D+?
应该匹配“ transportation openair”,并且[a-zA-Z]
将匹配最后一个单词(名词):
^(?P<pol>\\D+)(?P<d1>\\d)(?P<eng>\\D+)(?P<d2>\\d)\\D+?(?P<end>[a-zA-Z]+)$
您的问题是您与\\D+
匹配,它将匹配多个单词(包括空格)。 弄清楚最后一组单词是很有意义的。
因此,您需要使最后一组仅与非空白字符匹配,并且在最后一组与空白字符匹配之前。
这是一种模式,它与名为“ category”的组中的“ transportation openair”匹配,并与“ end”组中的“ noun”正确匹配。 因为我们在匹配category
使用了非贪心+
,所以我们需要一个$
来锚定end
组,使其实际上成为字符串中的最后一个单词。
re.match(r'(?P<pol>\D+)(?P<d1>\d)(?P<eng>\D+)(?P<d2>\d)(?P<category>\D+?)\W+(?P<end>\w+)$', tags).group('end')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.