I find kotlins regex kind of complicated. Usually I use it to find the first match, but it seems I don't understand something about how it is supposed to work because the code looks kind of awkward:
Copy code
regex.find(line)?.groupValues?.getOrNull(1)
Is this the correct way to find the first match of a regex result?
a
Arian Stolwijk
05/17/2020, 8:03 PM
Maybe use
destructured
to make it easier?
p
Paul Woitaschek
05/17/2020, 8:36 PM
But why does it have the whole string as the first match?
a
araqnid
05/18/2020, 6:01 AM
The destructured projection explicitly doesn’t,
val (g) = match.destructured
will assign the first match group to
g
. Although that’s not so convenient when you’re starting from an optional match.
regex.find(input)?.let { it.groupValues[1] }
would be what I’d write
m
Michael de Kaste
05/18/2020, 7:05 AM
@Paul Woitaschek regex engines explicitly use the first capture group to the full match. This isn't "kotlin's" regex that's 'kind of complicated'.
.NET, javascript and Java (languages I worked with) all have group 0 as the full match, that's just how regex works.
n
nkiesel
05/19/2020, 6:41 AM
this would not be required if your regexp always matches the whole line. But consider
Regex("my \\w+").find("hello my dear friend")?.value
which returns
my dear
. W/o that you always would have to have at least one