捕获重复组的正则表达式

Regular expression capturing a repeated group(捕获重复组的正则表达式)

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

问题描述

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

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

我似乎总是捕获最后一个组,即 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.

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

本文标题为:捕获重复组的正则表达式

基础教程推荐