Writing the same regular expression logic in multiple JVM languages

I tried writing three regular expressions in a the most common JVM languages.

  1. Find first match
  2. Find all matches
  3. Replace first match

My experience in these languages range from use it many times a week (Groovy) to this is the first thing I’ve written in it (Clojure).

I’m going to be using these in a presentation. So if you see anything in here that is a bad idiom in the language, do let me know!


The WordPress syntax highlighter doesn’t have Kotlin as a choice

val text = "Mary had a little lamb"
val regex = Regex("\\b\\w{3,4} ")
val text = "Mary had a little lamb"
val regex = "\\b\\w{3,4} ".toRegex()
  .map { it.groupValues[0] }
  .forEach { print(it) }
val text = "Mary had a little lamb."
val wordBoundary = "\\b"
val threeOrFourChars = "\\w{3,4}"
val space = " "
val regex = Regex(wordBoundary +
  threeOrFourChars + space)
println(regex.replaceFirst(text, "_"))


Thanks to dhinojosa for the code review and feedback that smart quotes don’t require backslashes inside!

val text = "Mary had a little lamb"
val regex = """\b\w{3,4} """.r
val optional = regex findFirstIn text
println(optional.getOrElse("No Match"))
val text = "Mary had a little lamb."
val regex = """\b\w{3,4} """.r
val it = regex findAllIn text
it foreach print
val text = "Mary had a little lamb."
val wordBoundary = """\b"""
val threeOrFourChars = """\w{3,4}"""
val space = " "
val regex = new Regex(wordBoundary + threeOrFourChars + space)
println(regex replaceFirstIn(text, "_"))


  re-find #”\b\w{3,4} ", 
          "Mary had a little lamb"))
  re-seq #”\b\w{3,4} ", 
          "Mary had a little lamb"))
(ns clojure.examples.example
(defn Replacer []
   (def text "Mary had a little lamb.")
   (def wordBoundary "\\b")
   (def threeOrFourChars "\\w{3,4}")
   (def space " ")
   (def regex (str wordBoundary 
        threeOrFourChars space))
   (def pat (re-pattern regex))
       text pat "_")))


def text = 'Mary had a little lamb'
def regex = /\b\w{3,4} /

def matcher = text =~ regex
print matcher[0]
def text = 'Mary had a little lamb'
def regex = /\b\w{3,4} /

def matcher = text =~ regex
print matcher.findAll().join(' ')
def text = 'Mary had a little lamb'
def regex = /\b\w{3,4} /

def matcher = text =~ regex
print matcher.findAll().join(' ')

JavaOne – Improve your Groovy Kung-Fu

“Improve your Groovy Kung-Fu”

Speaker: Dierk Koenig

For more blog posts from JavaOne, see the table of contents

Use cases

  • Spock for testing
  • System automation – Docker
  • Jenkins scripting console and pipelines

Recommends Groovy ref card

Groovy idioms

“a” == “b” – check if two strings are equal

a in col – check if element in a collection

${‘0’*10} – print 10 times

use Collections, {

type .xyz vs .getXyz()

use “it” (default) instead of creating a variable for grep

catch(all) – vs catch(Exception e)

gpars dataflows – specify what want to do in tasks, but not the order [I had trouble following this part]

@Grab(“groupid:artifactid:version”) – get dependency from Maven Central. Can specify a resolver as first parameter if want to use an alternate one. Not worth it though because then as much work as setting up a project.

Command line

  • groovy -e “print 1” – command line eval
  • groovyconsole – interactive UI

My take: I like that he showed code that he wrote and pointed out idioms. Seeing well written code is helpful for seeing good practices. I also realized that I know more than I thought. Many of the items in this post I knew existed but aspire to use more. Or things I do and would like more of the team to do.

upgrading from jenkins 1 to jenkins 2

The first Jenkins LTS (long term support) release fro Jenkins 2.0 came out this week.  It is Jenkins 2.7.1 and is available for download here. CodeRanch is running 1.640 and we decided to upgrade shortly after the LTS release came out. There have been numerous weekly releases for 2.0. We wanted the LTS release so it is a little more stable.


Another moderator at CodeRanch installed Jenkins and Sonar originally. Unfortunately, they are mixed together in the data directory. Anyway, I started by taking a backup in case I want to go back to 1.X at any point or mess it up/ I’m not terribly worried because our Jenkins install has 5 jobs on it. Worse case, I can do a fresh install and re-create them. I want to try upgrading first though since it is easier (at least in theory.)

tar -cvf jenkins1-20060709-bkp.tar *

The tar file was 1.2 GB. This is because it includes the job workspaces and Sonar.


Conveniently our Jenkins install is just the war. So I backed up the old war and uploaded the new one:

mv jenkins.war jenkins1-bkp

Starting up with Jenkins 2

Loading Jenkins showed a nice banner with a big button to click


So I clicked the “upgrade now” button. That led to a prompt to ask if I wanted to install some pipeline related plugins.

I said yes so they installed.

Then I got another button that Jenkins was ready. Still looks the same and my jobs are still there.


When I went to look at the plugins that were installed, I saw “Warning: This Jenkins instance requires a restart. Changing the state of plugins at this time is strongly discouraged. Restart Jenkins before proceeding.”. Which makes sense. Odd the upgrade process didn’t prompt me to restart. I did it myself at this point.

Existing Jobs

The five existing jobs ran the same way as they did before upgrade.  That odd phrasing was because what really happened was:

  • Three jobs were successful
  • One job hasn’t been run in ages and was clearly an old experiment. I deleted it.
  • One job has been failing for a few days and nobody noticed. It doesn’t have email notification and is triggered by the main job. (It was failing because it was relying on an Ant 1.9 feature and Jenkins was using Ant 1.8.) I upgraded Ant and then it was good. I also added email notification so that doesn’t happen again.

Jenkins 2 claims to be fully backwards compatible. As near as I can tell, this is true. I didn’t run into any issues related to migration. I even felt comfortable deleting the giant backup file at this point.

What did change

What I noticed very quickly

  1. The job configuration screen now tab navigation which takes you right to a section on the page.
  2. The configuration of external tools is now under Maven Jenkins > Global Tool Configuration instead of Manage System.

Actually using pipelines

Granted Pipelines were available in Jenkins 1. Looking at the jobs we had, we have three distinct steps (the main build runs CI and Sonar and then a JavaDoc build runs.) It would be good to have the Sonar one as a top level citizen and equal to the JavaDoc one. I decided to try to re-write the whole thing in Groovy (rather than calling the existing jobs) to see how hard it would be. I also split the Sonar step out into its own stage. This would have been more difficult to do as a separate job because I’d have had to pass the Sonar revision number and hack at it to use the same workspace. (I know how to do both those things – after all the original JavaDoc job uses an absolute path to the Ant script to run in the original workspace – but still.)

As an aside, I had trouble finding the workspace.

Figuring out email notification was a pain. In particular, getting it to email on every failure and first success just like the default used to be. But the rest worked pretty easily and end to end it only took me a couple hours (and 37 test builds) – it’s a pretty simple set of jobs. And now the email list is one place for all the JForum stages so we won’t have the JavaDoc build failing and nobody knowing again. The script wound up being:

def emailRecipients = 'xxx@gmail.com'

node {
 // hack to get workspace variable - https://issues.jenkins-ci.org/browse/JENKINS-33511
 env.WORKSPACE = pwd()
 try {
 stage 'Build'
 // poll SVN and check out updates if changes
 checkout poll: true, scm: [$class: 'SubversionSCM', additionalCredentials: [], excludedCommitMessages: '', excludedRegions: '', excludedRevprop: '', excludedUsers: '', filterChangelog: false, ignoreDirPropChanges: false, includedRegions: '', locations: [[credentialsId: 'e10831de-302f-4c1d-9518-fa7fb81bab9e', depthOption: 'infinity', ignoreExternalsOption: true, local: '.', remote: 'https://xxxx/svn/xxx']], workspaceUpdater: [$class: 'UpdateUpdater']]
 // call Ant
 def antHome = tool 'apache-ant-1.9.7'
 sh "${antHome}/bin/ant clean compile jacoco dist-work"
 step([$class: 'JUnitResultArchiver', testResults: 'qa/reports/*.xml'])
 stage 'Sonar'
 sh "${antHome}/bin/ant sonar -DprojectVersion=${env.SVN_REVISION}"
 stage 'JavaDoc'
 sh "${antHome}/bin/ant javadocs"
 // archive only if run successfully
 step([$class: 'JavadocArchiver', javadocDir: "${env.WORKSPACE}/docs/api", keepAll: false])
 // without this, you don't get emails
 currentBuild.result = 'SUCCESS' 
 } catch (err) { 
 // without this, you don't get emails
 currentBuild.result = 'FAILURE' 
 throw err
 } finally {
 echo "currentBuild.result: ${currentBuild.result}"
 // send email whether job failed or not
 step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: emailRecipients, sendToIndividuals: false])