go to previous page   go to home page   go to next page
String original = "Pi is 3.14159265, but e is 2.718281828";
String fixed    = original.replaceAll( "([0-9]+)\\.([0-9])([0-9])[0-9]*", "$1.$2$3" );
System.out.println( fixed );

Answer:

Pi is 3.14, but e is 2.71

replaceFirst()

The String class has a method

public String replaceFirst( String RE, String replacement )

which works like replaceAll() except now only the first substring that matches RE is replaced with replacement.


QUESTION 15:

What is the output of the following fragment?

String original = "Mr. Smith was scene walking away from the scene of the crime.";
String fixed    = original.replaceFirst( "scene", "seen" );
System.out.println( fixed );