Could we add `fun String.startsWith(` `prefix:...
# stdlib
n
Could we add
fun String.startsWith(
prefix: Regex,
ignoreCase: Boolean = false
): Boolean
(and also
endsWith
)? The
ignoreCase
parameter would be debatable, but since the
String
variant has it and it's easy to add to the implementation, I would vote to keep it.
e
how is it easy? you have to re-create the Regex to change its
i
flag
anyhow, without
ignoreCase
this is
prefix.matchesAt(string, 0)
n
easy because we can use
val pattern = if (ignoreCase) Regex(prefix.pattern, RegexOption.IGNORE_CASE) else prefix
. Of course, we still have to wrap that in
^
and
.*
.
e
you're losing other flags
and if the regex is already case insensitive, shouldn't
ignoreCase = false
flip it?
with
matchesAt
you don't need to wrap it in any anchors
n
loosing: yes. so
val pattern = if (ignoreCase) Regex(prefix.pattern, prefix.options + RegexOption.IGNORE_CASE) else prefix
. But yes, if the pattern already contains an
?i
, then
startsWith(pattern, false)
would not do the right thing (assuming the in-pattern flags overwrite the outside-of-pattern flags). So perhaps makes more sense to drop the
ignoreCase
parameter for the `Regex`variant.
matchesAt
works nicely for
startsWith
, but not so nice for
endsWith
.
e
as far as I'm aware, there's no efficient way to implement
endsWith
on non-regular regexes (as found in basically everything aside from Google RE2)
n
yeah, I agree. But I'm not too concerned about performance here, and really am aiming for convenience and consistency. I can write
fileName.contains(".kt")
and
filename.contains("Regex("""\.kt""")
, and I can write
fileName.endsWith(".kt")
, so why not also
fileName.endsWith(Regex("""\.kt"""))
?