I find kotlins regex kind of complicated. Usually ...
# announcements
p
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
Maybe use
destructured
to make it easier?
p
But why does it have the whole string as the first match?
a
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
@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
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
()
in every regex to get a matched string back