我试图使用groovy中的一些正则表达式函数从git repo中提取Version标签。
def command = "\"C:/Program Files (x86)/Git/bin/sh.exe\" --login -i -c \"git ls-remote user@mysever:myproject.git refs/tags/[vV]*?.*?.*?\""
def proc = command.execute()
proc.waitFor()
def str = proc.in.text
def pattern = ~/^refs\/tags\/[vV][0-9]+\.[0-9]+\.[0-9]+$/
System.out.println("is everything a string? " + str.tokenize().every{ it instanceof String })
System.out.println("String: $str")
System.out.println("split: ${str.split()}")
System.out.println("contains refs/tags/V0.0.0?: ${str.split()*.trim().contains('refs/tags/V0.0.0')}")
System.out.println("contains refs/tags/V0.0.1?: ${str.split()*.trim().contains('refs/tags/V0.0.1')}")
System.out.println("grep: " + ['refs/tags/V0.0.0', 'refs/tags/V0.0.1'].grep(pattern))
System.out.println("split grep: " + str.split().grep(pattern))
System.out.println("split findAll: " + str.split().findAll{ it =~ pattern })
我的输出是这样的:
String: SHA1asdf refs/tags/V0.0.0
SHA1fdsa refs/tags/V0.0.0^{}
SHA1hgfd refs/tags/V0.0.l
SHA1dfgh refs/tags/V0.0.l^{}
split: [SHA1asdf, refs/tags/V0.0.0, SHA1asdf, refs/tags/V0.0.0^{}, SHA1hgfd, refs/tags/V0.0.l, SHA1dfgh, refs/tags/V0.0.l^{}]
contains refs/tags/V0.0.0?: true
contains refs/tags/V0.0.1?: false
grep: [refs/tags/V0.0.0, refs/tags/V0.0.1]
split grep: [refs/tags/V0.0.0]
split findAll: [refs/tags/V0.0.0]
为什么tokenize()。grep()不会产生预期的答案?
我正在使用 Groovy 2.3.6
更新:我添加了更多测试结果,查看代码和输出
答案 0 :(得分:2)
不确定原因,但您的版本V0.0.1
实际上是一个字符l
,而不是1
。
如果您只是运行以下示例(刚刚更改了str
),grep将正常工作:
def str = """
SHA1asdf refs/tags/V0.0.0
SHA1fdsa refs/tags/V0.0.0^{}
SHA1hgfd refs/tags/V0.0.1
SHA1dfgh refs/tags/V0.0.1^{}
"""
def pattern = ~/^refs\/tags\/[vV][0-9]+\.[0-9]+\.[0-9]+$/
System.out.println("String: $str")
System.out.println("tokenize: ${str.tokenize()}")
System.out.println("grep: " + ["refs/tags/V0.0.0", "refs/tags/V0.0.1"].grep(pattern))
System.out.println("tokenize grep: " + str.tokenize().grep(pattern))
生成
grep: [refs/tags/V0.0.0, refs/tags/V0.0.1]
tokenize grep: [refs/tags/V0.0.0, refs/tags/V0.0.1]