正则表达式捕获重复的组 [英] Regular expression capturing a repeated group

查看:78
本文介绍了正则表达式捕获重复的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式解析输入字符串.尝试捕获重复的组时出现问题.我似乎总是在匹配该组的最后一个实例.我曾尝试使用不情愿"(非贪婪)量词,但似乎遗漏了一些东西.有人可以帮忙吗?

I am trying to parse input string using regular expression. I am getting problem when trying to capture a repeating group. I always seem to be matching last instance of the group. I have tried using Reluctant (non greedy) quantifiers, but I seems to be missing some thing. Can someone help?

尝试使用正则表达式:

(OS)\\s((\\w{3})(([A-Za-z0-9]{2})|(\\w{3})(\\w{3}))\\/{0,1}){1,5}?\\r

(OS)\\s((\\w{3}?)(([A-Za-z0-9]{2}?)|(\\w{3}?)(\\w{3}?))\\/{0,1}?){1,5}?\\r

输入字符串:

OS BENKL/LHRBA/MANQFL\r\n

我似乎总是捕获最后一个组,即MANQFL组(MAN QFL),我的目标是将所有三个组(可以有1-5个组):

I always seem to capture last group which is MANQFL group (MAN QFL), and my aim is to get all three groups (there can be 1-5 groups):

(BEN KL) , (LHR BA) and (MAN QFL). 

任何帮助将不胜感激.

推荐答案

当您在正则表达式中重复捕获组时,捕获组仅存储上一次迭代匹配的文本.如果需要捕获多个迭代,则需要使用多个正则表达式. (.NET是唯一的例外.它的CaptureCollection提供捕获组所有迭代的匹配项.

When you repeat a capturing group in a regular expression, the capturing group only stores the text matched by its last iteration. If you need to capture multiple iterations, you'll need to use more than one regex. (.NET is the only exception to this. Its CaptureCollection provides the matches of all iterations of a capturing group.

这篇关于正则表达式捕获重复的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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