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)

1
  • What is the actual output? Commented Nov 1, 2013 at 8:35

3 Answers 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+?).

Sign up to request clarification or add additional context in comments.

Comments

1

*

stands for zero or more times, try replacing it with

+

Comments

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); } 

2 Comments

That passes the test, but I need to use regex so that input like 1JU3C_227.CBT is not erroneously replaced
You want to replace "." by "," only if it occured more than once...is that right??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.