简体   繁体   English

正则表达式:如何使用正则表达式捕获多个组中的一个? (在红宝石中)

[英]Regex: How do you capture one group among multiple groups using regex? (in ruby)

I have two groups of text: 我有两组文字:

firstgroup
(some content)
endgroup


secondgroup
(some content)
endgroup

I'm trying to just capture the first group (not the second group). 我试图捕获第一组(而不是第二组)。 I'm using this regular expression: 我正在使用以下正则表达式:

firstgroup(.|\n)*endgroup

For some reason, that regular expressions selects both first group and second group (probably because it looks at the very last "endgroup" above). 由于某种原因,该正则表达式同时选择了第一组和第二组(可能是因为它查看了上面的最后一个“ endgroup”)。 Is there a way to modify my regex such that I only select the first group (and not the second group)? 有没有办法修改我的正则表达式,使我只选择第一个组(而不选择第二个组)?

You need a lazy quantifier 您需要一个懒惰的量词

/firstgroup\n(.*?)\nendgroup/m

to end the group as soon as possible. 尽快结束小组。 See http://www.rubular.com/r/D6UkOnMYLj . 参见http://www.rubular.com/r/D6UkOnMYLj

(And you could use the /m flag to make the . match new lines.) (并且您可以使用/m标志使.匹配新行。)

string=<<EOF
firstgroup
(some content)
endgroup


secondgroup
(some content)
endgroup
EOF

puts string.split(/endgroup/)[0] + "endgroup"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM