0

I have a text field where someone can enter a string.

But I need to return an integer using that string.

I know how to convert strings to integers, but how do I separate any letters & punctuation from the string so it leaves only numbers?

4 Answers4

2

Try this code:

String str = "a1?2.33/4tyz.7!8x";
str = str.replaceAll("\\D", "");

Now str will contain "1233478"

MCHAppy
  • 1,012
  • 9
  • 15
0

Match against regular expression. 0-9

Example has been given before. How to extract numbers from a string and get an array of ints?

Community
  • 1
  • 1
JohannisK
  • 535
  • 2
  • 10
0

You could replace all extra symbols with regular expression ant then call Integer.valueOf(). For example:

Integer.valueOf(src.replaceAll("[!0-9]",""));
dmitrievanthony
  • 1,501
  • 1
  • 15
  • 41
0

You need to replace all the values you don't want in your string and then parse the rest as an integer:

    String userInput = "Number 42 is the best";
    userInput = userInput.replaceAll("[^\\d]", '');
    return Integer.parseInt(test); //returns '42'

There is an existing post similar on how to do this here

Community
  • 1
  • 1