Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match multiple numbers between strings, process them and replace

Tags:

java

regex

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.

like image 713
Anusha Avatar asked Feb 03 '26 09:02

Anusha


1 Answers

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
like image 103
Rizwan M.Tuman Avatar answered Feb 06 '26 00:02

Rizwan M.Tuman