Home » Android » android – How to extract a number from a string

android – How to extract a number from a string

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am writting an application whereby to reset a password you will be sent an sms containing a reset code to confirm you as the owner of the account.. But am trying to build the app in such a way that it receives the broadcast of the received sms and get the specified integer only from the sms body.
Sample of the sms
We noticed you want to reset your password. Password reset code is 3242., Thanks

i like to get just the reset code=3242 from the whole sms body..
Thanks.

How to&Answers:

Use regex as

  String number = body.replaceAll("\D+","");

Or use a regex such as [^0-9] to remove all non-digits as

String number  = body.replaceAll("[^0-9]", "");