Thread
#stdlib
    a

    Ayfri

    8 months ago
    In almost all my projects I add these two methods, could it be a good idea to add them ?
    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
    fun String.get(regex: Regex) = replace(regex, "$1")
    That could be useful to add
    Javier

    Javier

    8 months ago
    I have my own stdlib which has those methods and a few more
    like
    second()
    ,
    secondOrNull()
    and so on
    e

    ephemient

    8 months ago
    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
    .
    mcpiroman

    mcpiroman

    8 months ago
    I'd like theremovemethods. The getis just sth. like
    match(regex).groups[0]
    ? If so, imo you should either you that or name this extension more like
    getFirstGroup
    .
    Klitos Kyriacou

    Klitos Kyriacou

    8 months ago
    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.
    Javier

    Javier

    8 months ago
    The first one can be implemented so
    fun String.remove(value: String) = replace(value, "")