Home > Blockchain >  RegEx: Match until an nth word
RegEx: Match until an nth word

Time:12-13

So I have the following cases:

> **Started by user** by Bla bla bla 
> **Started by a upstream** project by bla bla
> **Start by a commit** by more needless information

I need to get basically only get the strings only until the build cause For example "Start by user", but I don't if it will be user, upstream project or a commit. So I think I require a regex in this situation, but I'm sure on how to achieve that.

  CAUSE = "${currentBuild.getBuildCauses()[0].shortDescription}"

Only information I'm sure about that it will produce is " Started by a ****(I need the reason here - (user, upstream project, commit) | everything else should be ommited

End result expected:

Started by a user 
Started by an upstream project 
Started by a commit

CodePudding user response:

Depending on what your intention and use case really is you can get along like this:

CAUSE = currentBuild.getBuildCauses()[0].shortDescription
CAUSE.replaceAll("Started by a?", "").split(" ")[0] 

But I personally would check for the Cause.class, rather than using regex. This way you can also easily get the user name or upstream job or whatever the cause brings you (https://javadoc.jenkins-ci.org/hudson/model/Cause.html), like Cause.UserCause or Cause.UpstreamCause.

CodePudding user response:

Here is another way to do this.

script{
        def cause = currentBuild.getBuildCauses()[0]._class
        def message = ""
        if(cause.equals('hudson.model.Cause$UserIdCause')) {
            message = "Started by a user"
        } else if(cause.equals('hudson.model.Cause$UpstreamCause')) {
            message = "Started by an upstream project "
        }
    println message
}
  • Related