How to track the last element of one line with RegEx ?

Sometimes we need to get the last element of the line. We can do it by mesuring the line length and getting the character through String's charAt(int) method. However, we can rarely deal with the Strings natively representing only one line. Instead of splitting a String to get this separated representation, we can simply use a special RegEx symbol, z.

In our sample we want to replace all floating numbers where the number after the comma hasn't 2 characters:

public class ZRegexTest {

	@Test
	public void test() {
		String[] numbers = new String[] {"3.4", "3.33", "3.5", "3.0.4"};
		String[] expected = new String[] {"3.40", "3.33", "3.50", "3.0.40"};
		for (int i = 0; i < numbers.length; i++) {
			String result = numbers[i].replaceAll("(\\d+)(\\.)(\\d{1}\\z)", "$1$2$30");
			assertTrue("Result '"+result+"' should be the same as expected result '"+expected[i]+"'", result.equals(expected[i]));
		}
	}

}

This test checks if formatted String is equal to expected. If you remove \\z from the replaceAll statement, you'll see the test fails. It's because the presence of \\z guarantees that the number at the end of given input is replaced. Without it, consequently the second number will contain a supplementary 0, for example: 3.33 will be transformed at 3.303.

So \\z flag allows us to operate on the end of an input.