Identify and get a mobile number from a String - java

I need to extract a mobile number from a string. I have extracted numbers from string, but failed to get what I need.
Here is the input: a string contains an address and phone number.
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903"
I need to extract the mobile number, which is 92166-29903.
I use this method to check whether a string contains a mobile number or not:
private Boolean isMobileAvailable(String string)
{
Boolean ismobile = false;
if (string.matches("(?i).*M.*"))
{
ismobile = true;
}
return ismobile;
}
Used in a code as follows:
String mobilenumber="";
private void getMobileNumber(String sample)
{
int index = sample.indexOf("M");
String newString = "";
newString = sample.substring(index, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
}
Here, instead of mobile number, I am getting 147009211.
How can I identify the mobile number correctly from above string?

int index = sample.lastIndexOf("M");
String newString = sample.substring(index+2, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
If you want the "-" in your result,just delete mobileNumber = newString.replaceAll("[^0-9]", "");

try this code.
Method 1:
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903";
int value = input.lastIndexOf(":");
String s = input.substring(value + 1, input.length());
Log.d("reverseString", "" + s);
Method 2:
StringBuffer reverseString=new StringBuffer(input);
StringBuffer s1=reverseString.reverse();
int firstindex=s1.indexOf(":");
String finalstring=s1.substring(0, firstindex);
StringBuffer getexactstring=new StringBuffer(finalstring);
this code will give you exact mobile number that you want.

Related

How to extract a string between '#' and '.'

I want to extract a string between two characters "#" and the first ".".I just tried the code but my code is not appropriate and getting different output
//code
static String method(String s){
String result=s.substring(s.lastIndexOf("#"));
int index = result.indexOf(".");
String finalResult= result.substring(0,index);
return finalResult;//return
}
eg:abc#gmail.com
my output:#gmail
Expected output: gmail
From input gmail is identifies as a string between '#' and the first '.' after it.
But i am getting # in my output which is different from expected output. Help me out.
As per Javadocs:
Returns a string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" //(an empty string because there are no more characters after the 9th, i.e., there's no 10th character in "emptiness"; "emptiness" is a 9-letter word)
And if you debug your code, you will see
System.out.println("abc#gmail.com".lastIndexOf("#"));
produces 3
As mentioned by Scary Wombat, substring(position) is inclusive, and therefore s.substring(s.lastIndexOf("#")); will return substring containing '#' char.
Some extra note is that there are be many edge cases for which your code will fail, for example null string, string that does not contain '#' etc.
See suggestion code that tries to catch all edge cases, with test
#Test
public void testGetSubString(){
final String constant = "gmail";
final String input1 = "test#gmail.com";
final String input2 = "t.est#gmail.com";
final String input3 = "test##gmail.com";
final String input4ShouldBeNull = "test#gmailcom";
final String input5ShouldBeNull = "test#.gmailcom";
final String input6ShouldBeNull = "";
final String input7ShouldBeNull = null;
final String input8ShouldBeNull = "gmail.com";
assertEquals(constant, getSubString(input1));
assertEquals(constant, getSubString(input2));
assertEquals(constant, getSubString(input3));
assertNull(constant, getSubString(input4ShouldBeNull));
assertNull(constant, getSubString(input5ShouldBeNull));
assertNull(constant, getSubString(input6ShouldBeNull));
assertNull(constant, getSubString(input7ShouldBeNull));
assertNull(constant, getSubString(input8ShouldBeNull));
}
public String getSubString(final String input) {
if(input == null) {
return null;
}
final int indexOfAt = input.lastIndexOf('#');
if(input.isEmpty() || indexOfAt < 0 || indexOfAt >= input.length()-2) {
return null;
}
String suffix = input.substring(indexOfAt + 1);
final int indexOfDot = suffix.indexOf('.');
if(indexOfDot < 1) {
return null;
}
return suffix.substring(0, indexOfDot);
}

Java string manipulation for validity

Say for instance I have this string:
"His name is Justin Hoffman"
and need to check if it is a valid name:
In order for this to return true I need to make sure I have "His name" before "is" and I need "Justin Hoffman" after the "is" how can I check to see if I have the correct substring before "is" and the correct one after "is"
String sentence = "His name is Justin Hoffman";
String[] splitSentence = sentence.split(" is ");
String first = splitSentence[0]; // His name
String second = splitSentence[1]; // Justin Hoffman
boolean isTrue = (first.equals("His name") && second.equals("Justin Hoffman"));
String input = "His name is Justin Hoffman";
String requiredFirstName = "His name";
String requiredLastName = "Justin Hoffman";
String delimiter = " is ";
// Example 1
if (input.equals(requiredFirstName + delimiter + requiredLastName))
{
System.out.println("The input is OK");
}
// Example 2
int posi = input.indexOf(delimiter);
if (posi > 0) // found
{
String leftPart = input.substring(0, posi);
String rightpart = input.substring(posi + delimiter.length());
if (requiredFirstName.equals(leftPart) && requiredLastName.equals(rightpart))
{
System.out.println("The input is OK");
}
}
// Example 3
String[] parts = input.split(delimiter);
if (requiredFirstName.equals(parts[0]) && requiredLastName.equals(parts[1]))
{
System.out.println("The input is OK");
}
The second example is possibly the fastest one because it does not produce temporary strings. The third example is the slowest one. Be careful with special character in the delimiter because the split() function interprets the argument as a regular expression.

Replace anything within two brackets

I have this string:
String string = "The status is %status(" + randomString + ")%";
How can I replace the part between percent signs with anything, but without knowing randomString?
You can use String.replaceAll. An example:
String randomString = "asdf";
String string = "The status is %status(" + randomString + ")%";
String replacement = "myStatus";
String fString = string.replaceAll("%status(.*)%", replacement);
System.out.println(fString);
Which outputs:
The status is myStatus
The regex you want to use is %(.+)%, which matches %status(foo)% and %status(asidh37887123-48hsZXas;;fgfg)%.
To replace it, you can do string.replaceAll("%(.+)%", "anything").
This will turn The status is %status(foo)% to The status is anything.
Two ways to do it :
String string = "The status is %status(aaaaaaaaaaaaaaa)%";
int x = string.indexOf("%");
int y = string.lastIndexOf("%");
System.out.println(x);
System.out.println(y);
string = string.substring(0,x)+string.substring(y+1,string.length());
System.out.println(string);
string = "The status is %status(aaaaaaaaaaaaaaa)%";
string = string.replaceAll("%.+%", "");
System.out.println(string);
Result :

Android String format not working

I have a problem with String.format In android I want replace { 0 } with my id.
My this code not working:
String str = "abc&id={0}";
String result = String.format(str, "myId");
I think you should use replace method instead of format.
String str = "abc&id={0}";
str.replace("{0}","myId");
you have 2 ways to do that and you are mixing them :)
1.String format:
String str = "abc&id=%s";//note the format string appender %s
String result = String.format(str, "myId");
or
2.Message Format:
String str = "abc&id={0}"; // note the index here, in this case 0
String result = MessageFormat.format(str, "myId");
You have to set your integer value as a seperate variable.
String str = "abc&id";
int myId = 001;
String result = str+myId;
try this,
String result = String.format("abc&id=%s", "myId");
edit if you want more than one id,
String.format("abc&id=%s.id2=%s", "myId1", "myId2");
The syntax you're looking for is:
String str = "abc&id=%1$d";
String result = String.format(str, id);
$d because it's a decimal.
Other use case:
String.format("More %2$s for %1$s", "Steven", "coffee");
// ==> "More coffee for Steven"
which allows you to repeat an argument any number of times, at any position.

Assign a variable to a string of text that is between a certain delimiters Ex. “|” using Java

I have a string that I want to break down and assign different part of this string to different variables.
String:
String str ="NAME=Mike|Phone=555.555.555| address 298 Stack overflow drive";
To Extract the Name:
int startName = str.indexOf("=");
int endName = str.indexOf("|");
String name = str.substring(startName +1 , endName ).trim();
But I can't extract the phone number:
int startPhone = arg.indexOf("|Phone");
int endPhone = arg.indexOf("|");
String sip = arg.substring(startPhone + 7, endPhone).trim();
Now how can I extract the phone number that is between delimiter "|".
Also, is there a different way to extract the name using the between delimiter "=" & the first "|"
You can split on both = and | at the same time, and then pick the non-label parts
String delimiters = "[=\\|]";
String[] splitted = str.split(delimiters);
String name = splitted[1];
String phone = splitted[3];
Note that his code assumes that the input is formatted exactly as you posted. You may want to check for whitespace and other irregularities.
String[] details = str.split("|");
String namePart = details[0];
String phonePart = details[1];
String addressPart = details[2];
String name = namePart.substring(namePart.indexOf("=") + 1).trim();
String phone = phonePart.substring(phonePart.indexOf("=") + 1).trim();
String address = addressPart.trim();
I hope this could help.

Categories