0

Im a beginner to java and trying to build my own weather app. When getting the temperature, the output is

/?4°

or

/?-4°

Now I only need to get the temperature (4° or -4°). How can I achieve this? I already tried

str.replace('?',' ')

But that does nothing. My problem with

str.replaceAll('\\D', ' ')

is, that it also removes the - sign. I hope you can help me.

Knecko
  • 13
  • 1
  • 1
    Strings in java are immutable, meaning they cannot be changed. The method `str.replace('?',' ')` returns a new String where the characters are replaced. – Willem Mar 17 '20 at 21:35
  • Please read the `replace` docs, e.g., old but valid, https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char) – Dave Newton Mar 17 '20 at 21:36

1 Answers1

0

You can tweak your regex and use:

str = str.replaceAll('[^\\d-]', '')

This will replace all non digits nor hyphens.

Beware that you need to assign the result of str.replaceAll

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • It'd be good to address what the original issue was tho – RobOhRob Mar 17 '20 at 21:37
  • Well your original post did not contain the underlying issue, which I see you added now `Beware that you need to assign the result of str.replaceAll` – RobOhRob Mar 17 '20 at 22:11