Important thing to note regarding any req expressions in java is replaceAll method can replace a part of the String with regular expression in any String.
For matches method the entire String has to match regular expression and not just a part else matches returns false.
That is the important difference between replace and matches.
$ is used replace only if end of String is exact match to given reg expression like 991 below
System.out.println(newAlphanumeric.replaceAll("991$", "ABC"));
Below code is used to replace occurrence of ghi in String with X
System.out.println(newAlphanumeric.replaceAll("ghi", "X"));
Code to replace occurrence of every a ,e and i in String with AC .That is if we want to replace all the occurences of either a,e or i we use []
System.out.println(newAlphanumeric.replaceAll("[aei]", "AC"));
Code to replace occurrence of every a ,e and i in String with "the rain"
System.out.println(newAlphanumeric.replaceAll("[aei]", "the rain"));
Code to replace occurence of every a ,e and i in String only if a e and i is either followed by f or g i.e look for occurrence of af ,ag , ef,eg or if,ig with AC
System.out.println(newAlphanumeric.replaceAll("[aei][fg]", "the rain"));
Code below replaces any Harry or harry with tommy
System.out.println("Harry".replaceAll("[Hh]arry", "Tommy"));
Below we have carrot character but it is inside the square bracket. So it is not the same as ^ we discussed in previous example which looks for something at beginning of String. The one below will replace any thing other than b,h,i or 5 with X so it acts like a NOT
System.out.println("abcdefghijklmnopqrstuvwxyz5".replaceAll("[^bhi5]", "X"));
Below code replaces any occurences of a to f or 3-7 with x.Please note it does not have to be continous i.e we can have something like adfeg or 43756 or even repetitive like 3452333 etc and it will replace them all
System.out.println("abcdeFGHaaa123456789555".replaceAll("[abcdef34567]", "X"));
Below code does the same as above
System.out.println("abCdeFGHaa123456789".replaceAll("[a-f3-7]", "X"));
Above code only looks for lower case a-f as regular expressions are case sensitive.For upper case we can do something like A-F
System.out.println("abCdeFGH123456789".replaceAll("[a-fA-F3-7]", "X"));
Or we can do both upper and lower case using (?i) in the before reg expression.So the construct (?i) turns the case senstivity off
System.out.println("abCdeFGH123456789".replaceAll("(?i)[a-f3-7]", "X"));