Reputation: 303
I have the following string:
"Hard120109Missing or invalid shipper phone number"
How would I use Java to get the following:
"Missing or invalid shipper phone number"
Basically, I want to only retrieve the text after the last occurrence of a number.
Upvotes: 1
Views: 336
Reputation: 3180
String[] arr = yourString.split("[0-9]+");
String newString = arr[1]; //get string after first number
First, split your string by any digits, and then get your string from array
For different amounts of numbers:
String[] arr = yourString.split("[0-9]+", 2);
StringBuilder sb = new StringBuilder();
if (arr.length <= 1)
throw new RuntimeException("Invalid String");
for (int i = 1; i < arr.length; i++)
sb.append(arr[i]);
String newString = sb.toString();
Heres another way:
String newString = "";
try{
yourString.split("[0-9]+", 2)[1];
} catch(ArrayIndexOutOfBoundsException e){} //leaves newString as ""
Upvotes: 3
Reputation: 988
String str = "Hard120109Missing or invalid shipper phone number";
String newStr = "";
for (int i = str.length() - 1; i >= 0; i--) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) break;
newStr = ch + newStr;
}
Upvotes: 1
Reputation: 4880
You can use split
to get the last part of the String
String msg = "Hard120109Missing or invalid shipper phone number";
String val[] = msg.split("\\d+");
if (val.length > 1) {
System.out.println("Message= " + val[1]);
}
Output
Message= Missing or invalid shipper phone number
Upvotes: 1
Reputation: 2569
You could always loop (assume this is its own helper method):
for(int i = str.length()-1; i >= 0; i--) {
char c = str.charAt(i);
if(c >= '0' && c <= '9') {
return str.substring(i+1);
}
}
return "";
Upvotes: 0