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

Viewed 500

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 + "");
    }
}
3 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.

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);
     }
  }
  

First split the string into numbers and letters [2, aaa, 3, bbb, 4] and traverse the stream if the element is a number e.matches("\\d+") then multiply with 2 then collect to a new String value.

Try this:

String s= "2aaa3bbb4";
String[] str = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

String result = Arrays.stream(str).map(e -> e.matches("\\d+") ? String.valueOf(Integer.valueOf(e)*2) : e)
    .collect(Collectors.joining());

System.out.println(result);

Output:

4aaa6bbb8
Related