Reputation: 410
I have a string and i would like to extract the floats in it. I have successfully done it using the matcher.group() function but i only want to display them separately. Here is my code
String regex="([0-9]+[.][0-9]+)";
String input= "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(input);
while(matcher.find())
{
System.out.println("First float is "+matcher.group());
}
}
The answer i get is : First float is 1.00 First float is 1.04
But i want to say : First float is 1.00 Second Float is 1.04
How do i do that?
Upvotes: 0
Views: 90
Reputation: 3862
Use Following Method to convert number to ordinal form then use it to display
public static String ordinal(int i) {
String[] suffixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + suffixes[i % 10];
}
}
public static void main(String[] args) {
String regex = "([0-9]+[.][0-9]+)";
String input = "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int number = 1;
while (matcher.find()) {
System.out.println(ordinal(number++) + " float is " + matcher.group());
}
}
Upvotes: 1
Reputation: 30839
You can write a method that returns postfix like st
, nd
, rd
and use it in the code, e.g.:
private static String getPostFix(int number) {
if(number % 10 == 1) {
return "st";
} else if(number % 2 == 0) {
return "nd";
} else if(number % 3 == 0) {
return "rd";
} else {
return "th";
}
}
The code would be:
String regex="([0-9]+[.][0-9]+)";
String input= "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(input);
int i=0;
while(matcher.find()){
System.out.println((++i) + getPostFix(i) + " Float is :" + matcher.group());
}
Upvotes: 0
Reputation: 1040
You need to have a counter within loop, and based on counter write in output proper word. But rather start with displaying sth like "Float #n is: xxx" instead of words...
Upvotes: 0
Reputation: 171
Something like that maybe ?
int k = 1;
while(matcher.find())
{
System.out.println("Float " + k + " is "+matcher.group());
k++;
}
This will output something like: Float 1 is 1.00 Float 2 is 1.04
Upvotes: 5