0

I'm attempting to make the following replacement in java

@Test
public void testReplace(){
    String str = "1JU3C_2.27.CBT";
    String find = "(\\d*)\\.(\\d*)";
    String replace = "$1,$2";
    String modified = str.replaceAll(find, replace);
    System.out.println(modified);
    assertEquals("1JU3C_2,27.CBT", modified); //fails
}

However both full stops seem to be getting replaced. I'm looking at replacing only the numeric decimal. (i.e expecting output 1JU3C_2,27.CBT)

4

3 回答 3

3

Use (\\d+)\\.(\\d+) instead of (\\d*)\\.(\\d*).

Your regex asks to replace zero or more digits followed by a dot, followed by zero or more digits. So . in .CBT is matched as it has a dot with zero digits on both sides.

1JU3C_2.27.CBT has two dots with zero or more digits on both sides.

If you want to convert string like 5.67.8 to 5,67,8 use lazy matching as (\\d+?)\\.(\\d+?).

于 2013-11-01T08:38:48.837 回答
1

*

stands for zero or more times, try replacing it with

+

于 2013-11-01T08:39:46.130 回答
0

Instead do this:

public void testReplace()
{
   String str = "1JU3C_2.27.CBT";
   String modified = str.replaceFirst("[.]", ",");
   System.out.println(modified);
   assertEquals("1JU3C_2,27.CBT", modified); 
}
于 2013-11-01T08:38:28.197 回答