我有一个字符串,我想提取其中的浮点数。我已经使用matcher.group()函数成功完成了此操作,但我只想单独显示它们。这是我的代码
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());
}
}
我得到的答案是: 第一浮动为1.00 第一浮动为1.04
但是我想说: 第一浮动为1.00 第二浮动为1.04
我该怎么做?
答案 0 :(得分:5)
类似的东西?
int k = 1;
while(matcher.find())
{
System.out.println("Float " + k + " is "+matcher.group());
k++;
}
这将输出如下内容:浮点数1为1.00浮点数2为1.04
答案 1 :(得分:1)
使用以下方法将数字转换为序数形式,然后使用它来显示
public static String ordinal(int i) {
String[] sufixes = 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 + sufixes[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());
}
}
答案 2 :(得分:0)
您需要在循环内有一个计数器,并根据计数器写输出正确的字。而是从显示诸如“ Float #n is:xxx”之类的东西而不是单词开始。
答案 3 :(得分:0)
您可以编写一个返回后缀的方法,例如st
,nd
,rd
,并在代码中使用它,例如:
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";
}
}
代码为:
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());
}