【问题标题】:How to extract given array of string with numbers from string in groovy如何从groovy中的字符串中提取带有数字的给定字符串数组
【发布时间】:2020-01-10 07:14:28
【问题描述】:

我正在尝试使用 Jenkins 管道中的 groovy 检查来自 git 的 commit-msg 是否包含项目密钥为 Jira 的特定票号

def string_array = ['CO', 'DEVOPSDESK', 'SEC', 'SRE', 'SRE00IN', 'SRE00EU', 'SRE00US', 'REL']
def string_msg = 'CO-10389, CO-10302 new commit'

为了提取数字,我使用以下逻辑。

findAll( /\d+/ )*.toInteger()

不确定如何使用项目密钥提取准确的票号。 提前致谢。

【问题讨论】:

    标签: grails groovy jenkins-groovy


    【解决方案1】:

    您可以使用 Groovy 的查找运算符 - =~,结合 findAll() 方法来提取所有匹配的元素。为此,您可以创建一个匹配 CO-\d+ OR DEOPSDESK-\d+ OR ... 的模式,依此类推。您可以将项目 ID 保存在列表中,然后动态创建正则表达式模式。

    考虑以下示例:

    def projectKeys = ['CO', 'DEVOPSDESK', 'SEC', 'SRE', 'SRE00IN', 'SRE00EU', 'SRE00US', 'REL']
    def commitMessage = 'CO-10389, CO-10302 new commit'
    
    // Generate a pattern "CO-\d+|DEVOPSDEKS-\d+|SEC-\d+|...
    def pattern = projectKeys.collect { /${it}-\d+/ }.join("|")
    
    // Uses =~ (find) operator and extracts matching elements
    def jiraIds = (commitMessage =~ pattern).findAll()
    
    assert jiraIds == ["CO-10389","CO-10302"]
    
    // Another example
    assert ("SEC-1,REL-2001 some text here" =~ pattern).findAll() == ["SEC-1","REL-2001"]
    

    【讨论】:

      【解决方案2】:

      正则表达式可以组装得更简单一些:

      def projectKeys = ['CO', 'DEVOPSDESK', 'SEC', 'SRE', 'SRE00IN', 'SRE00EU', 'SRE00US', 'REL'] 
      def commitMessage = 'CO-10389, REL-10302 new commit'
      
      String regex = /(${projectKeys.join('|')})-\d+/
      
      assert ['CO-10389', 'REL-10302'] == (commitMessage =~ regex).findAll()*.first()
      

      您还可以选择另一个选项,通过匹配进行更精细的控制:

      def res = []
      commitMessage.eachMatch( regex ){ res << it[ 0 ] }
      assert ['CO-10389', 'REL-10302'] == res
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-14
        相关资源
        最近更新 更多