正则表达式捕获两个分隔符内出现的每个单词 [英] Regex capture every occurrence of a word within two delimiters

查看:53
本文介绍了正则表达式捕获两个分隔符内出现的每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个很长的文本字符串,并且每次在圆括号中提到 this 这个词时我都想捕获.我怎么能那样做?下面的模式只匹配第一个 this,忽略后面的每次出现:

Say I have a long string of text, and I want to capture every time the word this is mentioned within rounded brackets. How could I do that? The following pattern only matches the first this, ignoring every occurrence after:

/\(.*(this).*\)/g

例如,在以下文本中使用上面的模式:

For example, using the pattern above on the following text:

Etiam scelerisque, nunc ac egestas consequat, (odio this nibh euismod nulla, eget auctor orci nibh vel this nisi. Aliquam this eratvolutpat).

Etiam scelerisque, nunc ac egestas consequat, (odio this nibh euismod nulla, eget auctor orci nibh vel this nisi. Aliquam this erat volutpat).

只会返回单词odio之后的第一个this.

Will only return the first this after the word odio.

我做错了什么?

推荐答案

首先,不要贪心.

/\(.*?(this).*?\)/g

其次,如果您的目标是计算this"的出现次数,则正则表达式可能不是此处的正确工具.问题是您需要匹配结束定界符以确定第一个this"是封闭的,这意味着继续应用正则表达式将不会匹配已经使用的定界符集内的任何内容.

Secondly, if you're aiming to count the number of occurrences of 'this', a regex is probably not the right tool here. The problem is that you need to match the closing delimiter to determine that the first 'this' is enclosed, which means that continuing to apply the regex will not match anything inside that already-consumed set of delimiters.

我上面的正则表达式将捕获如下内容:

The regex I have above will catch things like:

foo (baz this bar) (foo this)

但不是(它只会匹配两次,每组定界符一次):

But not (it will only match twice, once for each set of delimiters):

foo (this this bar) baz (this this this)

尝试使用简单的单程扫描仪而不是正则表达式.另一种选择是使用两个正则表达式,一个将字符串分成封闭和非封闭部分,另一个在封闭区域内进行搜索.

Try using a simple single-pass scanner instead of a regex. Another alternative is to use two regular expressions, one to separate the string into enclosed and non-enclosed sections, and another to search within the enclosed regions.

这篇关于正则表达式捕获两个分隔符内出现的每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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