Reputation: 85
I want to replace non numeric characters with other non-numeric characters within a string. For instance in the following, change
4/14/2013%Univ. of Massachusetts-Amherst%Sacred Heart University%7-0
to
4/14/2013%Univ. of Massachusetts-Amherst%Sacred Heart University%7%0
I do not want to eliminate all hyphens, just the ones between the numbers. I was trying to use
line.replaceAll("-\\d+", "%\\d+");
but that replaces the second number with a literal d+
Upvotes: 0
Views: 158
Reputation: 70267
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");
Upvotes: 1
Reputation: 3976
change your parameters in string.replaceAll()
to this "-(\\d+)", "%$1"
, here $1
means group 1
captured by (\\d+)
Upvotes: 1