Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract 4-digit number from a String - Android [duplicate]

Tags:

regex

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.

like image 544
Gaurav Arora Avatar asked Nov 29 '16 05:11

Gaurav Arora


People also ask

How to extract numbers from a string using regular expressions?

How to extract numbers from a string using regular expressions? You can match numbers in the given string using either of the following regular expressions − Enter sample text: this is a sample 23 text 46 with 11223 numbers in it Digits in the given string are: 23 46 11223

How to get only 3 digit numbers from string using hive regular expressions?

For example, consider following example to get only 3 digit numbers from string using Hive regular expressions. SELECT REGEXP_EXTRACT (string, ' [0-9] {3}',0) AS Numeric_value FROM (SELECT 'Area code 123 is different for employee ID 112244.'

How do I make a string only have 4 digits?

You can go with \d {4} or [0-9] {4} but note that by specifying the ^ at the beginning of regex and $ at the end you're limiting yourself to strings that contain only 4 digits. My recomendation: Learn some regex basics. Show activity on this post.

How to extract at once all phone numbers from the text?

For example, you are looking for a way to extract at once all phone numbers from the text. This whole text has numerous sets of phone numbers scattered here and there randomly. You must be familiar with the "CONTROL + F" formula, which is built in most applications to help users find and highlight a certain string of data.


1 Answers

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(0);  // 4 digit number
}
like image 175
sasikumar Avatar answered Oct 12 '22 13:10

sasikumar