我有一个包含多个数字的字符串,必须再次处理并替换为相同的字符串。
例如:
让我说我有:
my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001
现在让我们说我想提取3647并对其进行乘法或除法或加法。我们将3647/100 = 36.47除以原来的数字替换为0001的字符串,并替换为00.01。
结果字符串应为:
my name is anusha, I am a noob in Java having reputation: 36.47 haha I am just kidding my actual reputation is 00.01
感谢您的帮助。我知道这对很多人来说很愚蠢,但我还在学习。
我尝试过:
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher("my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001");
makeMatch.find();
String inputInt = makeMatch.group();
System.out.println(inputInt);
但很明显它只会拿起第一个数字,因为我没有使用循环,我也不确定如何处理这个数字。
答案 0 :(得分:1)
试试这个:
final String regex = "\\d+";
String string = "my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001";
NumberFormat formatter = new DecimalFormat("00.00");
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
Float val=new Float(matcher.group(0));
val=val/100;
string=string.replace(matcher.group(0),formatter.format(val));
}
System.out.println(string);
}
输出:
my name is anusha, I am a noob in Java having reputation: 36.47 haha I am just kidding my actual reputation is 00.01
答案 1 :(得分:0)
答案 2 :(得分:0)
使用Pattern
和Matcher
,您可以找到数字的位置。
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(yourStringGoesHere);
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
然后您可以使用substring to add the period。
答案 3 :(得分:0)
我发现它here
public double isNumeric(String str){
String number="";
Double num=0;
for (char c : str.toCharArray()){
if (Character.isDigit(c)){
number+=c;
}
}
num = Double.parseDouble(number);
return num; //Then you can do whatever you want with this
}
对不起英文:/