返回重叠的正则表达式 [英] Returning overlapping regular expressions

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

问题描述

是否有一个正则表达式可以捕获一个表达式的所有实例,而不管它们是否重叠?

Is there a regular expression that will capture all instances of an expression, regardless of whether or not they overlap?

例如在 /abc/def/ghi 中,如果我想捕获所有以 / 开头的字符串.正则表达式 (/.*) 只返回整个字符串,但我希望它匹配 /def/ghi/ghi

E.g. in /abc/def/ghi if I want to capture all strings beginning with /. The regex (/.*) only returns the entire string, but I'd want it to match on /def/ghi and /ghi as well.

推荐答案

当然,匹配一个空字符串并在它后面放置一个前瞻,在捕获组中捕获 /.* :

Sure, match an empty string and place a look-ahead after it that captures /.* in a capturing group:

Matcher m = Pattern.compile("(?=(/.*))").matcher("/abc/def/ghi");
while(m.find()) {
  System.out.println(m.group(1));
}

会打印:

/abc/def/ghi
/def/ghi
/ghi

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

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