Firstly, you need two backslashes when you're dealing with regex in JAVA. The \\
escape sequence will translate to a single backslash at runtime. Now, in order to "capture" a piece of the initial expression, you need to use capture groups. By putting a piece of the regex expression in parentheses, you "capture" that piece of the string to be used in the replacement. So the initial string would be (\\d)-(\\d)
, where the first capture group is the digit before the hyphen and the second is the digit after.
To replace those digits back into the string, you need to use the syntax for capturing them back, which in JAVA is $. The resulting string should be $1%$2
, meaning "capture group 1, followed by a %, followed by capture group 2".
Your final line of code would look something like this:
line.replaceAll("(\\d)-(\\d)", "$1%$2");