捕获关键词后面的文字 [英] Capture text following the key words

查看:64
本文介绍了捕获关键词后面的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string text = "animal: leather, bacon, eagle. vegetable: timber, potato. mineral: granite, gem stones, waterfall.";
MatchCollection matches = Regex.Matches(text, @"(?'1'(animal:)|(mineral:)|(vegetable:).*?)", RegexOptions.ExplicitCapture);





我原以为这个返回3场比赛的代码:



动物:皮革,培根,鹰。,

蔬菜:木材,土豆。,并且

矿物:花岗岩,宝石,瀑布。



相反,返回的三个捕获只是关键字。为什么它没有捕获。*?关注这些关键字?如果我将以下文字贪婪,我只返回一个匹配,这是完整的字符串(正如我所料)。



干杯,



Mick



I was expecting this code to return 3 matches :

"animal: leather, bacon, eagle. ",
"vegetable: timber, potato. ", and
"mineral: granite, gem stones, waterfall."

Instead the three captures returned are the keywords only. Why is it not capturing the ".*?" following those keywords? If I make the following text greedy, I only get the one match returned, which is the full string (as I would expect).

Cheers,

Mick

推荐答案

搞定了。我需要围绕关键字选择添加额外的分组(以及如问题评论中所述的前瞻)。给出预期答案的正则表达式是:



@(?'1'((动物:))|(矿物:)| (蔬菜:))。*?(?=(动物:) |(矿物质:) |(蔬菜:) |
Got it. I needed to add additional grouping around the keyword selection (as well as having the look-ahead as described in the comments of the problem). The regex that gives the the expected answer is:

@"(?'1'((animal:)|(mineral:)|(vegetable:)).*?(?=(animal:)|(mineral:)|(vegetable:)|


))



线索是蔬菜:给出了正确的结果 - 它正在做

))

The clue was that the "vegetable:" was giving the correct result - it was doing
(animal:)|(mineral:)|(vegetable:.*?)



而不是


rather than

((animal:)|(mineral:)|(vegetable:)).*?


尝试这是否有效,只需在*之前添加空格??



Try if this works, Just added space before *?

Regex.Matches(text, @"(?'1'(animal:)|(mineral:)|(vegetable:). *?)"


这篇关于捕获关键词后面的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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