如何使用正则表达式匹配字符串中的第 n 次出现 [英] How to match nth occurance in a string using regular expression

查看:146
本文介绍了如何使用正则表达式匹配字符串中的第 n 次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

set string {rose is an flower jasmine is a flower rose is an flower rose is a colour jasmine is a flower}

从上面的字符串我想匹配rose is a flowerrose is a colour.

From the above string I want to match rose is an flower and rose is a colour.

所以我做了如下的正则表达式,

So I did regexp like below,

% puts [regexp -all {rose.+?(flower|colour)} $string]
3

从上面的 o/p 我们有三场比赛.

from the above o/p we had three matches.

% puts [regexp -all -inline {rose.+?(flower|colour)} $string]
{rose is an flower} flower {rose is an flower} flower {rose is a colour} colour

从上面的输出我期待:

{rose is an flower} {rose is an flower} {rose is a colur}

我不知道下面突出显示的词是怎么来的

I don't know how the below highlighted words are coming

{rose is an flower} flower {rose is an flower} flower {rose is a colour} colour
                    ^^^^^^                     ^^^^^^                    ^^^^^^

如果有人解释,我将不胜感激.

If someone explains, I would be grateful.

推荐答案

用括号括起来的子表达式 () 定义将分别为您提取的捕获组.来自手册:

Subexpressions surrounded by parentheses () define capture groups that will be extracted for you separately. From the manuals:

(正则表达式)`围绕一个或多个正则表达式的括号指定嵌套的正则表达式或几个正则表达式的选择.匹配嵌套正则表达式的子字符串被捕获并可以通过后向引用机制进行引用,并被捕获到指定为参数的相应匹配变量中命令.

(regular expression)` Parenthesis surrounding one ore more regular expressions specify a nested regular expression or choice of several regular expressions. The substring matching the nested regular expression is captured and can be referred to via the back reference mechanism, and alo captured into the corresponding match variable specified as an arbument to the command.

如果您不想提取捕获组,只需在括号的开头添加 ?:,在这种情况下,它们将只定义一个子表达式:

If you do not want to extract a capture group, you just add ?: at the beginning of the parentheses, in which case they'll just define a sub expression:

%puts [regexp -all -inline {rose.+?(?:flower|colour)} $string]
{rose is an flower} {rose is an flower} {rose is a colour}

这篇关于如何使用正则表达式匹配字符串中的第 n 次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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