正则表达式在一行的末尾抓取两个字符之间的所有内容

时间:2016-10-27 13:00:58

标签: regex groovy

我正在寻找创建一个正则表达式,它在两个“:”之间抓取文本,但前提是它是“最后一组”,例如:

\--- org.codehaus.groovy.modules.http-builder:http-builder:0.7.1

应该返回:

http-builder

应该注意的是,有可能得到类似的东西:

\--- org::codehaus::groovy::modules::http-builder:http-builder:0.7.1

因为输入不一定遵循惯例(基于手头的问题),但所需的信息总是在最后两个“:”中。

我尝试过以下一些(减去行尾):

1) (?<=\:).*(?=\:)
2) [^(.*:)].*[^(:.*)]
3) :.*: (this was the most successful, although I got the ":"s with the result but there are issues when there is more than one set of ":"s)

更多信息:

  • 我需要使用Groovy
  • 我可以使用流或文件(如果重要)阅读它

感谢阅读和任何帮助!

2 个答案:

答案 0 :(得分:3)

:([^:]*):[^:]*$

这意味着:

  • 序列必须以:
  • 开头
  • 然后开始捕获(
  • 捕获非冒号的所有字符[^:]*
  • 结束捕获) ...
  • ...在下一个冒号:
  • 然后是另一个字符序列[^:]*
  • 在该序列之后,行必须结束$(不再有序列)

或者,如果你可以使用非贪婪的比赛,你也可以使用

:(.*?):[^:]*$

.*表示捕获尽可能多的字符,而.*?表示捕获尽可能少的字符。但并非所有正则表达式实现都支持这一点。

答案 1 :(得分:3)

如何分割:并抓住倒数第二段?

['org.codehaus.groovy.modules.http-builder:http-builder:0.7.1', 
 /\--- org::codehaus::groovy::modules::http-builder:http-builder:0.7.1/].each { line ->

    assert 'http-builder' == line.split(':')[-2]
}