A: 

EDIT: Sorry, misread this as a javascript question. The general stuff about regular expressions below still applies, but the syntax/method name will differ in java.

In regex, \d is shorthand for [0-9], and + means "match one or more instances of the previous character". So \d+ means "match any number of sequential digits".

You can group matches in a string by surrounding what you want with parenthesis, and each group is assigned a number, starting from 1 and incrementing for each group. You can replace with a matched group by putting $1 (or $2, etc...) in the replacement string.

Finally, replaceAll isn't a function. You use regular replace, but add a g at the end of the regex to signify "global replace".

So you are looking for something like this:

txt = txt.replace(/(\d+)([a-z])/g, "$1*$2")
Ben Lee
oops, misread that as "javascript". sorry. don't know java.
Ben Lee
A: 

Beware that you might need to escape regexp-related symbols in the replacement string when using replaceAll (the second argument).

Vladimir Volodin
+2  A: 
package so4038148;

import static org.junit.Assert.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class MathExpr {

  private static final Pattern PAT_BEAUTIFY = Pattern.compile("(\\d+)(\\w)");

  /** The shortest code, but not the most efficient one. */
  public static String beautify1(String s) {
    return s.replaceAll("(\\d+)(\\w)", "$1*$2");
  }

  /** Still short, and doesn't need to compile the regex each time. */
  public static String beautify2(String s) {
    return PAT_BEAUTIFY.matcher(s).replaceAll("$1*$2");
  }

  /**
   * Use this when you have to do more complicated things with the captured
   * groups.
   */
  public static String beautify3(String s) {
    Matcher m = PAT_BEAUTIFY.matcher(s);
    if (!m.find()) {
      return s;
    }
    StringBuffer sb = new StringBuffer();
    do {
      m.appendReplacement(sb, m.group(1) + "*" + m.group(2));
    } while (m.find());
    m.appendTail(sb);
    return sb.toString();
  }

  @Test
  public void test() {
    assertEquals("20*a+4*y", beautify1("20a+4y"));
    assertSame("hello", beautify1("hello"));

    assertEquals("20*a+4*y", beautify2("20a+4y"));
    assertSame("hello", beautify2("hello"));

    assertEquals("20*a+4*y", beautify3("20a+4y"));
    assertSame("hello", beautify3("hello"));
  }
}
Roland Illig