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