正则表达式仅匹配最后一个项目 [英] RegEx only matches last item

查看:477
本文介绍了正则表达式仅匹配最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以崇高的态度编写自己的语法荧光笔.我认为它使用基于python的正则表达式.只是想匹配所有令牌,如:

说明str.bla,str.blub,str.yeah,str.no

我的正则表达式如下:

regex = "(description) (str\\.[\\w\\d]+)(,\\s*(str\\.[\\w\\d]+))*"

现在我希望第1组(描述")有1场比赛,第2组("str.bla")有1场比赛,而第4组("str.blub","str.yeah")有3场比赛, "str.no")

,但是我的最后一组("str.no")只有1场比赛.那里发生了什么事?

非常感谢!

解决方案

当您有重复的捕获组(例如(a)*(a)+等)时,捕获组将仅包含最后一个匹配项.

所以,如果我有正则表达式:

(123\d)+

和字符串:

123412351236

您会发现捕获组将仅包含1236.

我对此一无所知(除了硬编码要捕获的子组的数量),但是您可以尝试像这样捕获整个组:

regex = "(description) (str\\.[\\w\\d]+)((?:,\\s*(?:str\\.[\\w\\d]+))*)"

哪个应该给你

['description', 'str.bla', ', str.blub, str.yeah, str.no']

请注意元素的分组方式;您在列表中有3个项目,最后一个是较大列表中的列表".

I am trying to write my own syntax highlighter in sublime. I think it uses python-based regular expression. Just want to match all tokens in a row like:

description str.bla, str.blub, str.yeah, str.no

My regular expression looks like:

regex = "(description) (str\\.[\\w\\d]+)(,\\s*(str\\.[\\w\\d]+))*"

Now I expect 1 matches in group 1 ("description"), 1 match in group 2 ("str.bla") and 3 matches in my group no 4 ("str.blub", "str.yeah", "str.no")

but I have only 1 match in my last group ("str.no"). What's going on there?

Thanks a lot!

解决方案

When you have a repeated capture group, (e.g. (a)* or (a)+, etc), the capture group will contain only the last match.

So, if I have the regex:

(123\d)+

And the string:

123412351236

You will find that the capture group will contain only 1236.

I don't know any way around this (besides hard coding the number of subgroups to capture), but you can try capturing the whole group like so:

regex = "(description) (str\\.[\\w\\d]+)((?:,\\s*(?:str\\.[\\w\\d]+))*)"

Which should give you

['description', 'str.bla', ', str.blub, str.yeah, str.no']

Note how the elements are grouped; you have 3 items in the list, the last one being a 'list' within the larger list.

这篇关于正则表达式仅匹配最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆