Search code examples
javajsonbukkit

I want to trim a string in a way that a character will repeat only once


I am making a program in java, which gets title and current_version from this JSON API https://api.spigotmc.org/simple/0.1/index.php?action=getResource&id=<RESOURCE ID TO BE INPUT

It returns the name and the version, then I use it to make a link, and the format of link is pretty simple https://www.spigotmc.org/resources/<TITLE>.<ID>/

A lot of times it works, but in some cases like the title is returned as ChristmasPresents | [1.7-1.16], the the link to their page is https://www.spigotmc.org/resources/christmaspresents-1-7-1-16.39859/, So what I want to do is, trim it in a way that, all the special characters will be trimmed, but the result is like this https://spigotmc.org/resources/christmaspresents----1-7-1-16-.39859.

How can i cut those extra - I only want one, (It can repeat after a number or alphabet

Thanks


Solution

  • It seems like you want to replace all special characters with - but want no consecutive - in the output. For this, you could just use a regular expression to replaceAll \W+ with -:

    var title = "ChristmasPresents | [1.7-1.16]";
    title = title.replaceAll("\\W+","-");
    // "ChristmasPresents-1-7-1-16-"
    

    Note that this adds a - at the end, which you probably do not want. Unless I'm missing something String.strip will only strip whitespace, so the easiest way might be to replace the special chars with single spaces first, then strip, then replace the spaces with -:

    title = title.toLowerCase().replaceAll("\\W+"," ").strip().replace(" ", "-");
    // "christmaspresents-1-7-1-16"