Gaurav Arora Gaurav Arora - 8 days ago 6
Android Question

Regex to extract 4-digit number from a String - Android

I need to extract a 4-digit number from a string:

e.g "Your otp for the login is 7832. This code will expire at 12:43:09PM" from SMS in Android

I want to extract 7832 or any 4-digit code that comes within the string. I ensure that there will be only one 4-digit code in the string.

Please help me. I trying to use patterns like:

str.matches(".*\\\\d+.*");


But I'm not able to understand regexes much.

Answer
String data = "Your otp for the login is 7832. This code will expire at 12:43:09PM";

Pattern pattern = Pattern.compile("(\\d{4})");

//   \d is for a digit 
//   {} is the number of digits here 4.

Matcher matcher = pattern.matcher(data);
String val = "";
if (matcher.find()) {        
    val = matcher.group(1);  // 4 digit number
}