* match(): auto-select group 1 if there is one; support named groups
This commit is contained in:
parent
022e8f660a
commit
576b239a8c
|
@ -41,10 +41,10 @@ String.metaClass.pad = Number.metaClass.pad = { length = 2, padding = "0" -> del
|
||||||
/**
|
/**
|
||||||
* Return a substring matching the given pattern or break.
|
* Return a substring matching the given pattern or break.
|
||||||
*/
|
*/
|
||||||
String.metaClass.match = { String pattern, int matchGroup = 0 ->
|
String.metaClass.match = { String pattern, matchGroup = null ->
|
||||||
def matcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(delegate)
|
def matcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(delegate)
|
||||||
if (matcher.find())
|
if (matcher.find())
|
||||||
return matcher.group(matchGroup)
|
return matcher.groupCount() > 0 && matchGroup == null ? matcher.group(1) : matcher.group(matchGroup ?: 0)
|
||||||
else
|
else
|
||||||
throw new Exception("Match failed")
|
throw new Exception("Match failed")
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue