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.
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
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.'
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With