https://kotlinlang.org logo
#stdlib
Title
# stdlib
a

Ayfri

01/05/2022, 1:11 PM
In almost all my projects I add these two methods, could it be a good idea to add them ?
Copy code
fun String.remove(pattern: String) = replace(Regex(pattern), "")
fun String.remove(regex: Regex) = replace(regex, "")
Or at least the latter one ? I also have in multiple projects this extension
Copy code
fun String.get(regex: Regex) = replace(regex, "$1")
That could be useful to add
j

Javier

01/05/2022, 1:47 PM
I have my own stdlib which has those methods and a few more
like
second()
,
secondOrNull()
and so on
e

ephemient

01/05/2022, 3:46 PM
low value addition IMO. I work in a 330kLOC codebase. we do not have this extension, and from a structural search just now, there are zero usages that could be converted to either
.remove
or
.get
.
m

mcpiroman

01/05/2022, 3:55 PM
I'd like the`remove`methods. The `get`is just sth. like
match(regex).groups[0]
? If so, imo you should either you that or name this extension more like
getFirstGroup
.
k

Klitos Kyriacou

01/05/2022, 4:29 PM
I would not recommend the first one (
fun String.remove(pattern: String) = replace(Regex(pattern), "")
), because that would be inconsistent with how strings are treated in Kotlin. Unlike Java, Kotlin strings don't use implicit regexes. For example, whereas in Java, String.split() takes a regex as a string, in Kotlin the same function takes a literal string and does not interpret it as a regex. If you want it to be interpreted as a regex, pass a Regex argument.
3
j

Javier

01/05/2022, 5:17 PM
The first one can be implemented so
Copy code
fun String.remove(value: String) = replace(value, "")
👍 1