Created
April 17, 2012 16:09
-
-
Save EwanDawson/2407215 to your computer and use it in GitHub Desktop.
Idiomatic regex group capturing in Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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" |
Thanks @EwanDawson
I changed a bit but it also works
version = ("Hello world v1.01" =~ /.* v(\S*)/).with { hasGroup() ? it[0][1] : null }
Thanks for https://gist.github.com/EwanDawson/2407215#file-regex-capture-groovy-L7 as well!
Brilliantly executed!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for Line 7!