Question

I'm currently in a bit of a pickle.

I have a text box the user enters an address into, which is then sent as part of a url.

Currently, the solution I have works well with a single word - say "Brighton". But, if the user wants to add more detail to the query - say, a street address, I run into issues.

32 Sydney Street, Brighton, The City of Brighton and Hove BN1 4EP, UK

What would be the best way to change it to - I think a regex would do it, but I've always struggled with them.

32+Sydney+Street+Brighton+The+City+of+Brighton+and+Hove+BN1+4EP+UK

I'm currently doing this - which I think is messy, and well, just not good programming. It'd get even more gross if I add conditionals for '++'

String[] strArray = str.split(" ");
int strSize = strArray.length;

// Puts the split array back together, and add a plus between the words
str = "";
for (int i = 0; i < strSize; i++) {
    if (i < (strSize - 1))
        str += strArray[i] + "+";
    else
        str += strArray[i];
}

return str;

All the ways I'm thinking of run the risk of having two ++ in a row (which would invalidate the url), or are really 'gross' code.

Thanks for your time

Was it helpful?

Solution

Ollie, this should do it:

try {
    String resultString = subjectString.replaceAll("(?i)[^a-z0-9]+", "+");
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
    // Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
    // Non-existent backreference used the replacement text
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top