Skip to content

Instantly share code, notes, and snippets.

@EwanDawson
Created April 17, 2012 16:09
Show Gist options
  • Save EwanDawson/2407215 to your computer and use it in GitHub Desktop.
Save EwanDawson/2407215 to your computer and use it in GitHub Desktop.
Idiomatic regex group capturing in Groovy
// Using Matcher object returned by =~ operator
matcher = "Hello world v1.01" =~ /.* v(\S*)/
if (matcher.matches()) version = matcher[0][1]
assert version == "1.01"
// We can make this a little tidier using the 'with' method
version = ("Hello world v1.01" =~ /.* v(\S*)/).with { matches() ? it[0][1] : null }
assert version == "1.01"
@kraiz
Copy link

kraiz commented Feb 21, 2018

Thanks for Line 7!

@vladislav-yevtushenko
Copy link

Thanks @EwanDawson
I changed a bit but it also works
version = ("Hello world v1.01" =~ /.* v(\S*)/).with { hasGroup() ? it[0][1] : null }

@marcellodesales
Copy link

@chayneps
Copy link

Brilliantly executed!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment