Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to multiply each number in String using regex?

Tags:

java

regex

I need to increase each number String in two times. For example "32abcd54ab2abcd5" should be "64abcd108ab4abcd10". Is there any way to do this using regex, but not writing special function?

import java.util.regex.*;

class Test
{
    public static void main(String[] args)
    {
        String s= "2aaa3bbb4";
        Pattern p1 = Pattern.compile("(\\d+)");
        Matcher m1 = p1.matcher(s);
        String newString = m1.replaceAll(Integer.parseInt("$1") * 2 + "");
    }
}
like image 372
Denis_newbie Avatar asked Mar 03 '23 07:03

Denis_newbie


2 Answers

You may use a lambda in the Matcher#replaceAll as the replacement argument since Java 9:

String s= "2aaa3bbb4 67";
Pattern p1 = Pattern.compile("\\d+");
Matcher m = p1.matcher(s);
String result = m.replaceAll(x -> String.valueOf(Integer.parseInt(x.group()) * 2) );
System.out.println( result );
// => 4aaa6bbb8 134

A vartiation for older Java versions should be based on Matcher#appendReplacement:

String s= "2aaa3bbb4 67";
Pattern p1 = Pattern.compile("\\d+");
Matcher m = p1.matcher(s);
            
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, Integer.parseInt(m.group()) * 2 + "");
}
m.appendTail(sb);
System.out.println( sb.toString() );

See a Java demo.

like image 118
Wiktor Stribiżew Avatar answered Mar 05 '23 16:03

Wiktor Stribiżew


Not sure but Something like this might help.

  String oldString = "32abcd54ab2abcd5";
  char[] chars = oldString.toCharArray();
  for(char c : chars){
     if(Character.isDigit(c)){
        c = Integer.parseInt(c); 
        c = c *2 ;
        c = Integer.toString(int c);
     }
  }
  
like image 31
Prabesh Gouli Avatar answered Mar 05 '23 17:03

Prabesh Gouli