0

我想用字符串中的其他非数字字符替换非数字字符。例如在下面,改变

4/14/2013%Univ. of Massachusetts-Amherst%Sacred Heart University%7-0

4/14/2013%Univ. of Massachusetts-Amherst%Sacred Heart University%7%0

我不想消除所有连字符,只是数字之间的连字符。我试图使用

line.replaceAll("-\\d+", "%\\d+");

但这用文字替换了第二个数字d+

4

2 回答 2

1

把你的参数改成string.replaceAll()这个"-(\\d+)", "%$1",这里的$1意思是group 1被捕获(\\d+)

于 2013-04-17T03:31:33.450 回答
1

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");
于 2013-04-17T03:33:53.870 回答