How to fetch number from text in android - android

I want use register in my application and i should send password and verifyCode with SMS to users phones.
But i should read verifyCode from message and set automatically number into verifyCode EditText.
My message format :
Hi, welcome to our service.
your password 12345
your verifyCode 54321
How can i do it? Please help me <3

Assuming that the number of digits are fixed in password and verify codes (Generally they are same as default values), We can extract digits from the string and then find substring which has verify code. This assumption is for simplicity.
String numberOnly= str.replaceAll("[^0-9]", "");
String verifyCode = numberOnly.substring(6);
Here String verifyCode = numberOnly.substring(6); is getting last 5 digits of the string which is your verification code. You can also write numberOnly.substring(6,10); to avoid confusions.
But this is prone to errors like StringIndexOutOfBoundsException, So whenever you want to get substring which is starting from index i till the end of the string, always write numberOnly.substring(i).

There are a lot ways to do this. You can use some complicated regex or use a simple spilt method.
Try this,
String str = "Hi, welcome to our service.\n"
+ "\n"
+ "your password \n"
+ "12345\n"
+ "\n"
+ "your verifyCode \n"
+ "54321";
// Solution #1
String[] parts = str.split("\n");
System.out.println(parts[3]);
System.out.println(parts[6]);
// Solution #2
String PAT = "(password|verifyCode)\\s+(\\d+)";
Pattern pats = Pattern.compile(PAT);
Matcher m = pats.matcher(str);
while (m.find()) {
String grp = m.group(2);
System.out.println(grp);
}

Related

how to remove special character from string except + in android?

I am fetching number from contact book and sending it to server. i get number like this (+91)942 80-60 135 but i want result like this +9428060135.+ must be first character of string number.
Given your example you want to replace the prefix with a single + character. You also want to remove other non-numeric characters from the number string. Here's how you can do that:
String number = "(+91)942 80-60 135";
number = "+" + number.replaceAll("\\(\\+\\d+\\)|[^\\d]", "");
The regex matches any prefix (left paren followed by a + followed by one or more digits, followed by a right paren) or any non digit character, and removes them. This is concatenated to a leading + as required. This code will also handle + characters within the number string, e.g. +9428060135+++ and +(+91)9428060135+++.
If you simply wanted to remove any character that is not a digit nor a +, the code would be:
String number = "(+91)942 80-60 135";
number = number.replaceAll("[^\\d+]", "");
but be aware that this will retain the digits in the prefix, which is not the same as your example.
You can use String.replace(oldChar, newChar). Use the code below
String phone = "(+91)942 80-60 135"; // fetched string
String trimmedPhone = phone.replace("(","").replace(")","").replace("-","").trim();
I hope it will work for you.
check this. Pass your string to this function or use as per code goes
String inputString = "(+91)942 80-60 135";
public void removeSpecialCharacter(String inputString) {
String replaced = inputString.replaceAll("[(\\-)]", "");
String finalString = replaced.replaceAll(" ", "");
Log.e("String Output", " " + replaced + " " + second);
}

regex skips the first match

The regex
.*([0-9]{3}\\.[0-9]{2}).*
finds one match in "some short sentence 111.01 ", but it failed to match the first occurrence "111.01" in "some short sentence 111.01 & 222.02 "
I tried the lazy quantifier .*([0-9]{3}\\.[0-9]{2})?.* or .*([0-9]{3}\\.[0-9]{2}).*? for no avail.
Please help, I need to get both occurrences, here is my code.
Thank you
Pattern myPattern = Pattern.compile(".*([0-9]{3}\\.[0-9]{2}).*");
Matcher m = myPattern.matcher(mystring);
while (m.find()) {
String found = m.group(1);
}
you need to remove ".*"s. Try this:
String mystring = "some short sentence 111.01 & 222.02 ";
Pattern myPattern = Pattern.compile("([0-9]{3}\\.[0-9]{2})");
Matcher m = myPattern.matcher(mystring);
while(m.find()) {
System.out.println("Found value: " + m.group(1) );
}
output:
Found value: 111.01
Found value: 222.02
The leading and trailing ".*" cause you to match the entire string in one match. All the lazy quantifier does in your case is controls you getting the first, not last, occurrence in the subject.

how to get text with using substring

I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).

Regular expression with hebrew

I have text like:
לשלום קוראים לי משהmy test is עלות 39.40, כל מיני data 1.1.2015 ויש גם data 123456 מידע
This text have Hebrew and English characters, I need to eliminate all except the 6 digit number (may be 5, this num: 123456).
Can you help me with regular expression for this?
Tried:
String patternS = "[אבגדהוזחטיכךלמםנןסעפףצץקרשתa-fA-F0-9]{5,10}.*";
Pattern pattern = Pattern.compile(patternString);
With no success
To match everything except the number use:
\d+(?:[^\d]\d+)+|[\p{L}\p{M}\p{Z}\p{P}\p{S}\p{C}]+
String resultString = subjectString.replaceAll("\\d+(?:[^\\d]\\d+)+|[\\p{L}\\p{M}\\p{Z}\\p{P}\\p{S}\\p{C}]+", "");
This will give you every 6 didgit combination in your string.
(\d{6,6})
We can't give you a more detailled regex since we do now know the pattern of those strings.
In case there is always the "data " prefix you can also use this to make the pattern more accurate:
data (\d{6,6})
Try something like this:
String patternS = "(\d{5,6})";
Pattern pattern = Pattern.compile(patternS);
Matcher m = pattern.matcher(yourText);
int number = Integer.parseInt(m.group(1));
where yourText is the Hebrew/English text you want to match.
This would work for this specific example.
String s = " לשלום קוראים לי מש my test is עלות 39.40, כל מיני data 1.1.2015 ויש גם data 123456 מידע1234";
System.out.println(s.replaceAll(".*\\b(\\d{5,6})\\b.*", "$1"));

Android Logging Strings with newline character or <br>

It seems that if you call
String text = "String<br>String";
Log.d(TAG, text);
it automatically parses the String to take two lines. The same goes for new line (\n) characters. That makes debugging more complicated. Is there a way to tell the logger to give me the exact String?
The arguments to the methods in Log class are Java strings, so escaping special characters is just like in Java. For example,
String text = "String\nString";
Log.d("TEST!!", text);
Will give you:
D/TEST!!﹕ String
String
while:
String text = "String\\nString";
Log.d("TEST!!", text);
will give you:
D/TEST!!﹕ String\nString
in the logcat.
As far as <BR>, I'm not seeing the same effect as you. Specifically,
String text = "String<br>String";
Log.d("TEST!!", text);
Produces:
D/TEST!!﹕ String<br>String
So I am unable to reproduce your actual problem. However, in general special characters in the Log strings are escaped just like any other Java strings. The logger is dumb and there's no settings to automatically escape special characters; you'll have to do this yourself for arbitrary strings. The Log methods just turn around and call println_native.
I use System.getProperty("line.separator")
ArrayList<String> txts = new ArrayList<String>();
txts.add("aoeuaeou");
txts.add("snhsnthsnth");
String msg = TextUtils.join(System.getProperty("line.separator"),txts);
Log.d(TAG, "Bla bla bla: "+ msg );
show in the log like
Bla bla bla: aoeuaeou
snhsnthsnth
At the end of the message, a trailing space seems to be needed.
Log.i("tag", "My message with a blank line following.\n ");
or
Log.i("tag", "Variable 1: " + v1 + " Variable 2: " + v2 + "\n ");

Categories

Resources