I have a string that contains multiple numbers which have to be processed and replaced in the same string again.
For example:
let's say I have:
my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001
Now lets say I'd like to extract 3647 and multiply or divide or add something to it. Let's divide 3647/100 = 36.47 and replace with the original number in string same for 0001 and replace by 00.01.
Result String should be:
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
Appreciate your help. I know this is silly for many but I'm still learning.
I tried doing:
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);
But obviously it only picks up the first number because i did not use a loop, also I'm not really sure how to process the number.
Try this:
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);
}
Output:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With